Title Link: Hdu_5314_happy King
Test instructions
Give a tree of n nodes, point the right value;
Find the difference between the maximum and minimum values for a pair (x, y) that satisfies x!=y and x to Y paths <=D;
Exercises
Or the point of the tree, in the statistical answer to the root of the first order of the minimum value, and then use the maximum value minus D to find how many meet the answer.
1#include <bits/stdc++.h>2 #defineF (I,A,B) for (int i=a;i<=b;++i)3 using namespacestd;4typedef pair<int,int>P;5typedefLong Longll;6 Const intn=1e5+7;7 8 intn,k,g[n],v[n*2],nxt[n*2],ed,w[n],t;9 intVis[n],size[n],mx[n],mi,tot,root;Ten P Dis[n]; One ll ret; A -InlinevoidAdgintXintY) {v[++ed]=y,nxt[ed]=g[x],g[x]=Ed;} - voidInit () {F (I,1, N) g[i]=0, vis[i]=0; ed=0, ret=0;} the - voidDfs_size (intUintFA) - { -size[u]=1, mx[u]=0; + for(intI=g[u];i;i=Nxt[i]) - if(v[i]!=fa&&!Vis[v[i]]) + { ADfs_size (v[i],u), size[u]+=Size[v[i]]; at if(Size[v[i]]>mx[u]) mx[u]=Size[v[i]]; - } - } - - voidDfs_root (intRintUintFA) - { in if(Size[r]-size[u]>mx[u]) mx[u]=size[r]-Size[u]; - if(MX[U]<MI) mi=mx[u],root=u; to for(intI=g[u];i;i=Nxt[i]) + if(v[i]!=fa&&!Vis[v[i]]) - Dfs_root (r,v[i],u); the } * $ voidDfs_dis (intUintMiintMxintFA)Panax Notoginseng { -Mi=min (Mi,w[u]), mx=Max (Mx,w[u]); the if(mx<=mi+k) dis[++tot]=P (MI,MX); + for(intI=g[u];i;i=Nxt[i]) A if(v[i]!=fa&&!Vis[v[i]]) the Dfs_dis (v[i],mi,mx,u); + } - $LL Calc (intUintMiintmx) $ { -ll ans=0; -tot=0, Dfs_dis (U,MI,MX,0); theSort (dis+1, dis+tot+1); -F (I,1, tot)Wuyi { the intP=lower_bound (dis+1, dis+i+1, P (Dis[i].second-k,0))-dis; -ans+=i-p; Wu } - returnans; About } $ - voidDfsintu=1) - { -Mi=n,dfs_size (U,0); ADfs_root (U,u,0); +Ret+=calc (Root,w[root],w[root]), vis[root]=1; the for(intI=g[root];i;i=Nxt[i]) - if(!vis[v[i]]) ret-=Calc (v[i],w[root],w[root]); $ for(intI=g[root];i;i=Nxt[i]) the if(!Vis[v[i]]) DFS (v[i]); the } the the intMain () - { inscanf"%d",&t); the while(t--) the { Aboutscanf"%d%d",&n,&k); the init (); theF (I,1, N) scanf ("%d", w+i); theF (I,1, N-1) + { - intx, y; thescanf"%d%d",&x,&y);Bayi ADG (x, y), ADG (y,x); the } theDFS (), printf ("%lld\n", ret*2); - } - return 0; the}
View Code
Hdu_5314_happy King (Point division of the tree)