标签:dfs strong 树形dp nes line data code put mem
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 38859 Accepted Submission(s): 7140
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 int n; 5 const int maxn=1e4+5; 6 struct Edge{ 7 int v,w,next; 8 }edge[maxn<<1]; 9 int f[maxn],g[maxn],fa[maxn]; //f第一步往下走的走远距离,g第一步往往上走的组就远距离 10 11 int head[maxn],cnt; 12 void init(){ memset(head,-1,sizeof(head)),cnt=0; for(int i=1;i<maxn;i++) f[i]=g[i]=fa[i]=0; } 13 void add(int u,int v,int w){ 14 edge[cnt].v=v; 15 edge[cnt].w=w; 16 edge[cnt].next=head[u]; 17 head[u]=cnt++; 18 } 19 20 int dfs(int u,int pre){ ///自底往上 21 fa[u]=pre; 22 for(int i=head[u];~i;i=edge[i].next){ 23 int x=edge[i].v; 24 if(x!=pre){ 25 f[u]=max(f[u],edge[i].w+dfs(x,u)); 26 } 27 } 28 return f[u]; 29 } 30 31 void dfs2(int u,int pre){ ///自上往下 32 g[u]=g[pre]; 33 int t=0; 34 for(int i=head[pre];~i;i=edge[i].next){ 35 int v=edge[i].v,w=edge[i].w; 36 if(v==fa[pre]) continue; //祖先的祖先 37 if(v==u) t=w; 38 else g[u]=max(g[u],f[v]+w); 39 } 40 // if(pre!=0) 41 g[u]+=t; 42 for(int i=head[u];~i;i=edge[i].next){ 43 if(edge[i].v!=pre) dfs2(edge[i].v,u); 44 } 45 } 46 47 int main(){ 48 while(~scanf("%d",&n)){ 49 init(); 50 for(int i=2,d1,d2;i<=n;i++){ 51 scanf("%d%d",&d1,&d2); 52 add(i,d1,d2); 53 add(d1,i,d2); 54 } 55 dfs(1,0); 56 dfs2(1,0); 57 58 for(int i=1;i<=n;i++){ 59 printf("%d\n",max(f[i],g[i])); 60 } 61 } 62 return 0; 63 }
标签:dfs strong 树形dp nes line data code put mem
原文地址:https://www.cnblogs.com/qq-1585047819/p/11941050.html