标签:ted insert img src manage art 技术 fine put
InputInput file contains multiple test cases.In each case there is natural number N (N<=10000) in the first line, followed by (N-1) lines with descriptions of computers. i-th line contains two natural numbers - number of computer, to which i-th computer is connected and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input are separated by a space.OutputFor each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).Sample Input
5 1 1 2 1 3 1 1 1
Sample Output
3 2 3 4 4
/* 树形dp,方程好像不明显 不难发现,从每个点出发的最长链有两种可能,一种是贯穿他的子树,另一种是从他的父亲节点穿出去 可以用两个dfs,第一个不考虑其父亲节点的情况,只得出其贯穿子树的最长链 第二个dfs,将父亲节点考虑上,比一比怎样更优 所以我们应该维护两个值,最大和次大,以满足考虑父亲节点时的工作。 如果这个点在从父亲结点出发的最长链上时就考虑他与父亲相连的那条边加上他父亲连出去的次长链能否对其更新 否则,就用他与父亲相连的那条边加上他父亲连出去的最长链更新 */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; #define maxn 10010 int mx1[maxn],mx2[maxn],mx1id[maxn],mx2id[maxn],head[maxn*2]; int n,num; struct node{ int to,v,pre; }e[maxn*2]; void Insert(int from,int to,int v){ e[++num].to=to;e[num].v=v; e[num].pre=head[from];head[from]=num; e[++num].to=from;e[num].v=v; e[num].pre=head[to];head[to]=num; } void dfs1(int fa,int u){ for(int i=head[u];i;i=e[i].pre){ int v=e[i].to; if(v==fa)continue; dfs1(u,v); if(mx2[u]<mx1[v]+e[i].v){ mx2[u]=mx1[v]+e[i].v; mx2id[u]=v; if(mx2[u]>mx1[u]){ swap(mx2[u],mx1[u]); swap(mx2id[u],mx1id[u]); } } } } void dfs2(int fa,int u){ for(int i=head[u];i;i=e[i].pre){ int v=e[i].to; if(v==fa)continue; if(v==mx1id[u]){ if(mx2[v]<mx2[u]+e[i].v){ mx2[v]=mx2[u]+e[i].v; mx2id[v]=u; if(mx2[v]>mx1[v]){ swap(mx2[v],mx1[v]); swap(mx2id[v],mx1id[v]); } } } else if(mx2[v]<mx1[u]+e[i].v){ mx2[v]=mx1[u]+e[i].v; mx2id[v]=u; if(mx2[v]>mx1[v]){ swap(mx2[v],mx1[v]); swap(mx2id[v],mx1id[v]); } } dfs2(u,v); } } int main(){ freopen("Cola.txt","r",stdin); int x,y; while(scanf("%d",&n)!=EOF){ memset(head,0,sizeof(head));num=0; memset(mx1,0,sizeof(mx1));memset(mx2,0,sizeof(mx2)); memset(mx1id,0,sizeof(mx1id));memset(mx2id,0,sizeof(mx2id)); for(int i=2;i<=n;i++){ scanf("%d%d",&x,&y); Insert(i,x,y); } dfs1(-1,1); dfs2(-1,1); for(int i=1;i<=n;i++){ printf("%d\n",mx1[i]); } } }
标签:ted insert img src manage art 技术 fine put
原文地址:http://www.cnblogs.com/thmyl/p/6979442.html