标签:输出 put while iostream wal 遍历 test algorithm 多少
1 4 2 3 2 1 2 4 2 2 4
1 4
int dfs(int u,int pre){ for(int i = head[u];i;i = edge[i].next){ int v = edge[i].to; if(v == pre)continue; dfs(v,u); if(f1[u] < f1[v] + edge[i].dis) { f2[u] = f1[u]; f1[u] = f1[v] + edge[i].dis; } else f2[u] = max(f2[u],f1[v] + edge[i].dis); } ans = max(ans,f1[u] + f2[u]); return ans; }
# include <iostream> # include <cstdio> # include <cstring> # include <algorithm> using namespace std; const int N = 1e5 + 10002; const int M = 2e5 + 10002; const int INF = 0x3f3f3f3f; int n,m,cnt,head[N]; int read() { int ans=0,f=1; char i=getchar(); while(i<‘0‘||i>‘9‘){if(i==‘-‘)f=-1;i=getchar();} while(i>=‘0‘&&i<=‘9‘){ans=ans*10+i-‘0‘;i=getchar();} return ans*f; } struct Edge{ int to,next; int dis; }edge[M]; void AddEdge(int u,int v,int res){ Edge E1 = {v,head[u],res}; edge[++cnt] = E1;head[u] = cnt; Edge E2 = {u,head[v],res}; edge[++cnt] = E2;head[v] = cnt; } long long f1[N],f2[N],ans; int dfs(int u,int pre){ for(int i = head[u];i;i = edge[i].next){ int v = edge[i].to; if(v == pre)continue; dfs(v,u); if(f1[u] < f1[v] + edge[i].dis) { f2[u] = f1[u]; f1[u] = f1[v] + edge[i].dis; } else f2[u] = max(f2[u],f1[v] + edge[i].dis); } ans = max(ans,f1[u] + f2[u]); return ans; } void Init(){ memset(head,0,sizeof head); memset(f1,0,sizeof f1); memset(f2,0,sizeof f2); cnt = ans = 0; } void Getmap(){ Init(); n = read(), m = read(); int x,y,z; for(int i = 1;i < n;i++){ x = read();y = read(); AddEdge(x,y,1); } dfs(1,-1); ans += 1; for(int i = 1;i <= m;i++){ x = read(); if(x <= ans)printf("%d\n",x - 1); else printf("%d\n",ans - 1 + (x - ans) * 2); } } int main(){ int T; T = read(); while(T--) Getmap(); return 0; }
标签:输出 put while iostream wal 遍历 test algorithm 多少
原文地址:http://www.cnblogs.com/lzdhydzzh/p/7642134.html