1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N=1e5+7; 4 vector < vector <int> > g(N); 5 int d1[N],d2[N],d[N]; 6 bool visit[N]; 7 struct node { 8 int id; 9 int w; 10 }; 11 queue <node> q; 12 int n,m; 13 void dfs (int rt) { 14 memset (visit,0,sizeof(visit)); 15 while (!q.empty()) q.pop(); 16 node tmp={rt,0}; 17 q.push(tmp); visit[tmp.id]=1; d[rt]=0; 18 while (!q.empty()) { 19 tmp=q.front(); q.pop(); 20 for (int i=0;i<g[tmp.id].size();i++) { 21 int _next=g[tmp.id][i]; 22 if (!visit[_next]) { 23 node k={_next,tmp.w+1}; 24 q.push(k); visit[k.id]=1; d[_next]=k.w; 25 } 26 } 27 } 28 return ; 29 } 30 int find_max () { 31 int ans=0; int k; 32 for (int i=1;i<=n;i++) 33 if (d[i]>ans) { 34 ans=d[i]; 35 k=i; 36 } 37 return k; 38 } 39 void my_copy (int *a,int *b) { 40 for (int i=1;i<=n;i++) 41 a[i]=b[i]; 42 } 43 int main () 44 { 45 int T; scanf ("%d",&T); 46 while (T--) { 47 scanf ("%d",&n); 48 for (int i=1;i<=n;i++) g[i].clear(); 49 for (int i=1;i<=n-1;i++) { 50 int u,v; scanf ("%d %d",&u,&v); 51 g[u].push_back(v); 52 g[v].push_back(u); 53 } 54 int x1,x2; 55 dfs (1); x1=find_max(); 56 dfs (x1); x2=find_max(); 57 my_copy (d1,d); 58 dfs (x2); 59 my_copy (d2,d); 60 scanf ("%d",&m); 61 while (m--) { 62 int k,p; scanf ("%d %d",&k,&p); 63 int len=max (d1[k],d2[k]); 64 if (p<=len) printf("%d\n",p+1); 65 else printf("%d\n",min (n,len+(p-len)/2+1) ); 66 } 67 } 68 return 0; 69 }
感谢金牌果善意的提醒~~~树形dp还是有点麻烦。。
抓住青春的尾巴。。。