GalaxyOJ-1015 (Thinking)

topic

Problem 1015: 根
Time Limit: 4000 ms Memory Limit: 262144 KB

Problem Description

One day, Little B got a tree with n nodes. The extremely boring little B wants to find a point such that when this point is the root, the sum of the depths of all points is the largest. But Xiao B turned on his phone and found that his favorite re:creator was updated again, so this boring task is left to you.

For the top 30% of the data, n<=1000.

For the top 100% of the data, n<=1000000.

Input

The first line has a number n, the next n-1 lines, each line has two numbers, representing an edge.

Output

An integer per line represents the point of the maximum value of the sum of the depths of all points.
If the maximum value is the same, output points with a smaller number

Sample Input

5
2 1
3 1
4 2
5 3

Sample Output

4

analysis

  • This question is fairly simple, don’t care about the depth and the specifics, first take a certain point (I use 1) as the root by default, and then find that every time the root is changed to the point o connected to it, the depth of the point in the subtree o All will decrease by one, and the depth of other points will increase by one, and the total depth will increase -sz[o]+n-sz[o].
  • Do dfs twice, find the size of each subtree the first time, and get the answer the second time.

program

#include <cstdio>
#define Add(x,y) (to[++num]=head[x],head[x]=num,V[num]=y)
#define For(x) for(int h=head[x],o=V[h]; h; o=V[h=to[h]])
int head[1000005],to[2000005],V[2000005],num;
int n,sz[1000005],Max,ans;

void dfs(int x,int Fa,int dep){
    sz[x]=1;
    For(x) if (o!=Fa){
        dfs(o,x,dep+1);
        sz[x]+=sz[o];
    }
}

void Dfs(int x,int Fa,int delta){
    if (delta>Max) Max=delta,ans=x;
    if (delta==Max && ans>x) ans=x;
    For(x) if (o!=Fa)
        Dfs(o,x,delta-sz[o]+n-sz[o]);
}

int main(){
    scanf("%d",&n);
    for (int i=1,uu,vv; i<n; i++) scanf("%d%d",&uu,&vv),Add(uu,vv),Add(vv,uu);
    dfs(1,0,0);
    Dfs(1,0,0);
    printf("%d",ans);
}

Guess you like

Origin blog.csdn.net/jackypigpig/article/details/78491725