刚开始连树形dp,~~
树形dp不仅能连dp,还能练dfs.. 练建邻接表额~~
基本完全参考别人~~~
http://www.cnblogs.com/kuangbin/archive/2012/08/28/2659915.html
#include <iostream> #include <cstring> #include <cstdio> #define MAXM 20000 #define MAXN 20000 #define INF 0x3f3f3f3f #define BUG printf("here!\n") using namespace std; struct node { int u,v,len; }; node edge[MAXM]; int first[MAXN],next[MAXM]; int maxx[MAXN],smaxx[MAXN]; int maxxid[MAXN],smaxxid[MAXN]; int dp[MAXN],cc; inline void add_edge(int u,int v,int w) { edge[cc].u=u; edge[cc].v=v; edge[cc].len=w; next[cc]=first[u]; first[u]=cc; cc++; edge[cc].u=v; edge[cc].v=u; edge[cc].len=w; next[cc]=first[v]; first[v]=cc; cc++; } void dfs1(int u,int p) { maxx[u]=0; smaxx[u]=0; int i; for(i=first[u];i!=-1;i=next[i]) { int v=edge[i].v; if(edge[i].v==p) continue; dfs1(edge[i].v,edge[i].u); if(smaxx[u]<maxx[v]+edge[i].len) { smaxx[u]=maxx[v]+edge[i].len; smaxxid[u]=v; if(smaxx[u]>maxx[u]) { int t=maxx[u]; maxx[u]=smaxx[u]; smaxx[u]=t; t=maxxid[u]; maxxid[u]=smaxxid[u]; smaxxid[u]=t; } } } } void dfs2(int u,int p) { int i,v; for(i=first[u];i!=-1;i=next[i]) { v=edge[i].v; if(v==p) continue; if(maxxid[u]==v) { if(smaxx[v]<smaxx[u]+edge[i].len) { smaxx[v]=smaxx[u]+edge[i].len; smaxxid[v]=u; if(smaxx[v]>maxx[v]) { int t=maxx[v]; maxx[v]=smaxx[v]; smaxx[v]=t; t=maxxid[v]; maxxid[v]=smaxxid[v]; smaxxid[v]=t; } } } else { if(smaxx[v]<maxx[u]+edge[i].len) { smaxx[v]=maxx[u]+edge[i].len; smaxxid[v]=u; if(smaxx[v]>maxx[v]) { int t=maxx[v]; maxx[v]=smaxx[v]; smaxx[v]=t; t=maxxid[v]; maxxid[v]=smaxxid[v]; smaxxid[v]=t; } } } dfs2(v,u); } } int main() { int n; while(scanf("%d",&n)!=EOF) { int i; memset(first,-1,sizeof(first)); memset(next,-1,sizeof(next)); cc=0; memset(maxx,0,sizeof(maxx)); memset(smaxx,0,sizeof(smaxx)); memset(maxxid,0,sizeof(maxxid)); memset(smaxxid,0,sizeof(smaxxid)); for(i=2;i<=n;i++) { int u,l; scanf("%d%d",&u,&l); add_edge(i,u,l); } dfs1(1,-1); dfs2(1,-1); for(i=1;i<=n;i++) printf("%d\n",maxx[i]); } return 0; }