「MCOI-03」村国 (洛谷P7043)题解

· · 题解

(考场上没特判n==1调了快一个小时......)

原题P7043

看完题目后很容易想到暴力解法,首先这是一棵树,每次先找出当前好感度最高的村庄,更新与之相连的村庄的好感度,再找出更新后好感度最高的村庄进行下一轮更新。复杂度为O(mn)

然后跑去看数据范围,啥?m<=1e18 ? ? ?

看到这个范围我们就知道复杂度里肯定不带m。(log m : ?)

手动模拟分析一下,如果假设当前好感度最高的村庄为A,一天结束后,发生更新的只有与A相连的村庄,也就是说,与A不相连的村庄的好感度一定还是小于A的,所以下次去旅行的村庄一定在A和与之相连的村庄中,不妨记与A相连的村庄中好感度最高的村庄为B,两村庄好感度之差为s,易知经过m-s天后s=0,在这m-s天中实际一直停留在村庄A中。之后则只会在A,B两个村庄中(今天在A则B加1,第二天则B>A,停留在B,再给A加一,第三天回到A......)所以此时只需判断一下m的奇偶性就行了。

几个坑点:

1.不开longlong()

2.当有村庄好感度相同时输出好感度最小的那个,所以在最后要处理一下

3.特判n=1......

最后上代码:(不要问那个DFS是什么,考场上懒得想函数名)

#include<bits/stdc++.h>
using namespace std;
#define N 2000010
#define out(x) printf("%d\n",(x))
int n,T,a[N],maxn,root,son,maxs;
long long m;
struct edge{
    int nex,t;
} e[N*2]; int head[N],tot;
inline void add(int x,int y) {
    e[++tot].t=y; e[tot].nex=head[x]; head[x]=tot;
}
inline int read() {
    int s=0,w=1; char ch=getchar();
    while(ch<'0'||ch>'9') { if(ch=='-') w=-1; ch=getchar();}
    while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
    return s*w;
}
void dfs(int x) {
    for(int i=head[x];i;i=e[i].nex) {
        int y=e[i].t;
        if(a[y]>maxs) son=y,maxs=a[y];
    }
}
int main()
{
    T=read();
    while(T) {
        T--;
        n=read(); scanf("%lld",&m);
        for(int i=1;i<=n;i++) {
            a[i]=read();                  
            if(a[i]>maxn) maxn=a[i],root=i;       
        }
        for(int i=1;i<n;i++) {
            int x,y; x=read(); y=read();
            add(x,y); add(y,x);
        }
        if(n==1) {
            printf("1\n"); continue;
        }
        dfs(root);
        if(m<a[root]-a[son]) printf("%d\n",root);
        else if(m==a[root]-a[son]) printf("%d\n",min(root,son));
        else {
            m-=(a[root]-a[son]);
            if(root<son) {
                if(m%2==0) printf("%d\n",root);
                else printf("%d\n",son);
            }
            else {
                if(m%2==0) printf("%d\n",son);
                else printf("%d\n",root);
            }
        }
        maxn=-1; maxs=-1; tot=0; son=0; root=0;
        memset(head,0,sizeof(head));
    }
    return 0;
}