hdu-2196 树形dp 求一个树中所有节点能到达的最远距离f[i] (其实也不难嘛!)

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N=1e4+7;
 4 struct T {
 5     int to;
 6     int w;
 7 };
 8 vector < vector <T> > g (N);
 9 int d[N][3];// d[i][0] 正向最大距离 d[i][1] 正向次大距离 d[i][2] 反向最大距离
10 int p[N]; // 正向最大距离所经过的子节点
11 int n;
12 void  dfs1(int root) {//求正向距离
13     p[root]=d[root][0]=d[root][1]=d[root][2]=0;
14     for (int i=0;i<g[root].size();i++) {
15         int _next=g[root][i].to;
16         int cost=g[root][i].w;
17         dfs1(_next);
18         if (d[root][0]<d[_next][0]+cost) {
19             d[root][1]=d[root][0];
20             d[root][0]=d[_next][0]+cost;
21             p[root]=_next;
22         }
23         else if (d[root][1]<d[_next][0]+cost)
24                 d[root][1]=d[_next][0]+cost;
25     }
26     return ;
27 }
28 void dfs2(int root) {//求逆向距离
29     for (int i=0;i<g[root].size();i++) {
30         int _next=g[root][i].to;
31         int cost=g[root][i].w;
32         if (_next!=p[root]) d[_next][2]=max (d[root][0],d[root][2])+cost;
33         else                d[_next][2]=max (d[root][1],d[root][2])+cost;
34         dfs2(_next);
35     }
36     return ;
37 }
38 int main ()
39 {
40     while (~scanf ("%d",&n)) {
41         for (int i=1;i<=n;i++) g[i].clear();
42         for (int i=2;i<=n;i++) {
43             int x,cost; scanf ("%d %d",&x,&cost);
44             T tmp={i,cost}; g[x].push_back(tmp);
45         }
46         int root=1;
47         dfs1(root);
48         dfs2(root);
49         for (int i=1;i<=n;i++) 
50             printf ("%d\n",max (d[i][0],d[i][2]));
51     }
52     return 0;
53 }

猜你喜欢

转载自www.cnblogs.com/xidian-mao/p/9026708.html