两遍DFS……
第一遍维护自己儿子到自己的
第二遍维护自己祖先到自己的
用了内嵌汇编……
//Lib #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<ctime> #include<iostream> #include<algorithm> #include<vector> #include<string> #include<queue> //#include<stack> #include<set> #include<map> using namespace std; //Macro #define rep(i,a,b) for(int i=a,tt=b;i<=tt;++i) #define drep(i,a,b) for(int i=a,tt=b;i>=tt;--i) #define erep(i,e,x) for(int i=x;i;i=e[i].next) #define irep(i,x) for(__typeof(x.begin()) i=x.begin();i!=x.end();i++) #define read() (strtol(ipos,&ipos,10)) #define sqr(x) ((x)*(x)) #define pb push_back #define PS system("pause"); typedef long long ll; typedef pair<int,int> pii; const int oo=~0U>>1; const double inf=1e100; const double eps=1e-6; string name="", in=".in", out=".out"; //Var struct E { int node,next; }e[2000008]; struct N { long long up,down,size; }node[1000008]; int stack[20000000],bak; char file[20000000],*ipos; int h[1000008],n,tot; void add(int a,int b){e[++tot].next=h[a];e[tot].node=b;h[a]=tot;} void DFS1(int fa,int u) { erep(i,e,h[u]) { if(e[i].node!=fa) { DFS1(u,e[i].node); node[u].size+=node[e[i].node].size; node[u].down+=node[e[i].node].down; } } node[u].down+=node[u].size; node[u].size++; } void DFS2(int fa,int u) { if(u!=1)node[u].up=node[fa].up+n-node[u].size+node[fa].down-(node[u].size+node[u].down); erep(i,e,h[u]) if(e[i].node!=fa)DFS2(u,e[i].node); } void CallDFS(void (*p)(int,int)) { __asm__ __volatile__ ( "mov %%esp,%0\n" "mov %1,%%esp\n" :"=g"(bak) :"g"(stack+20000000-1) : ); (*p)(0,1); __asm__ __volatile__ ( "mov %0,%%esp\n" : :"g"(bak) : ); } void Work() { fread(ipos=file,20000000,1,stdin); n=read();int a,b; rep(i,1,n-1) { a=read();b=read(); add(a,b),add(b,a); } void (*p)(int,int)=DFS1; CallDFS(p); p=DFS2; CallDFS(p); int pos=1; rep(i,1,n)if(node[i].up+node[i].down>node[pos].up+node[pos].down)pos=i; cout<<pos<<endl; } int main() { // freopen((name+in).c_str(),"r",stdin); // freopen((name+out).c_str(),"w",stdout); // Init(); Work(); return 0; }