标签:
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5935 Accepted Submission(s): 2985
AC代码:
1 # include <iostream> 2 # include <cstring> 3 using namespace std; 4 const int MAX = 10010; 5 struct Node 6 { 7 int to; 8 int len; 9 int next; 10 }tree[MAX * 2]; 11 int head[MAX]; 12 int tol = 0; 13 14 int Max[MAX]; 15 int sMax[MAX]; 16 int Maxid[MAX]; 17 int sMaxid[MAX]; 18 void add(int a, int b, int len) 19 { 20 tree[tol].to = b; 21 tree[tol].len = len; 22 tree[tol].next = head[a]; 23 head[a] = tol++; 24 25 tree[tol].to = a; 26 tree[tol].len = len; 27 tree[tol].next = head[b]; 28 head[b] = tol++; 29 } 30 void dfs1(int root, int f) 31 { 32 Max[root] = 0; 33 sMax[root] = 0; 34 for(int i = head[root]; i != -1; i = tree[i].next) 35 { 36 int son = tree[i].to; 37 if(son == f) 38 continue; 39 dfs1(son, root); 40 41 if(sMax[root] < Max[son] + tree[i].len) 42 { 43 sMax[root] = Max[son] + tree[i].len; 44 sMaxid[root] = son; 45 if(sMax[root] > Max[root]) 46 { 47 swap(sMax[root], Max[root]); 48 swap(sMaxid[root], Maxid[root]); 49 } 50 } 51 } 52 } 53 void dfs2(int root, int f) 54 { 55 for(int i = head[root]; i != -1; i = tree[i].next) 56 { 57 int son = tree[i].to; 58 if(son == f) 59 continue; 60 if(son == Maxid[root]) 61 { 62 if(tree[i].len + sMax[root] > sMax[son]) 63 { 64 sMax[son] = tree[i].len + sMax[root]; 65 sMaxid[son] = root; 66 if(sMax[son] > Max[son]) 67 { 68 swap(sMax[son], Max[son]); 69 swap(sMaxid[son], Maxid[son]); 70 } 71 } 72 } 73 else 74 { 75 if(tree[i].len + Max[root] > sMax[son]) 76 { 77 sMax[son] = tree[i].len + Max[root]; 78 sMaxid[son] = root; 79 if(sMax[son] > Max[son]) 80 { 81 swap(sMax[son], Max[son]); 82 swap(sMaxid[son], Maxid[son]); 83 } 84 } 85 } 86 dfs2(son, root); 87 } 88 } 89 int main() 90 { 91 int n; 92 while(scanf("%d", &n) != EOF) 93 { 94 memset(head, -1, sizeof(head)); 95 tol = 0; 96 for(int i = 2; i <= n; i++) 97 { 98 int a, len; 99 scanf("%d%d", &a, &len); 100 add(i, a, len); 101 } 102 dfs1(1, -1); 103 dfs2(1, -1); 104 for(int i = 1; i <= n; i++) 105 printf("%d\n", Max[i]); 106 } 107 return 0; 108 }
标签:
原文地址:http://www.cnblogs.com/lyf-acm/p/5795843.html