1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
   | #include <iostream> #include <algorithm> #include <string.h>
  using namespace std; const int maxn = 1e4+5;
  struct edge{     int to,next,w;     edge() = default;     edge(int a,int b,int c):to(a),next(b),w(c) {} }e[maxn];
  int cnt,head[maxn];
  void add(int u,int v,int w) {     e[++cnt] = edge(v,head[u],w);     head[u] = cnt; }
  int n,f[maxn][3],node[maxn];
  void init() {     cnt = 0;     memset(head,0,sizeof head);     memset(f,0,sizeof f);     memset(node,0,sizeof node); }
  void dfs(int u) {     for (int i = head[u]; i; i = e[i].next) {         int v = e[i].to;         int w = e[i].w;         dfs(v);         if (f[u][0] <= f[v][0] + w) {             f[u][1] = f[u][0];             f[u][0] = f[v][0] + w;             node[u] = v;         } else if (f[u][1] < f[v][0] + w)             f[u][1] = f[v][0] + w;     } }
  void Dfs(int u) {     for (int i=head[u]; i; i=e[i].next) {         int v = e[i].to;         int w = e[i].w;         if (node[u] == v)             f[v][2] = max(f[u][2],f[u][1]) + w;         else             f[v][2] = max(f[u][2],f[u][0]) + w;         Dfs(v);     } }
  int main() {
      while (scanf("%d",&n) != EOF) {         init();         for (int i=2; i<=n; i++) {             int u,w;             scanf("%d%d",&u,&w);             add(u,i,w);         }         dfs(1);         Dfs(1);         for (int i=1; i<=n; i++)             printf("%d\n",max(f[i][0],f[i][2]));     }     return 0; }
 
  |