// 树形dp , 父子兄弟法构建树形结构 , 状态方程 t[i].vis += t[t[i].child].novis ||
t[i].novis += t[t[i].child].maxx()
1
Source Code
2
3 Problem: 2342 User: eth1
4 Memory: 456K Time: 94MS
5 Language: C ++ Result: Accepted
6 Source Code
7 #include < iostream >
8 #include < algorithm >
9 using namespace std;
10 const int M = 6001 ;
11 struct node
12 {
13 int father,brother,child;
14 int vis,novis;
15 int maxx()
16 {
17 return max(vis,novis);
18 }
19 void init()
20 {
21 father = brother = child = novis = 0 ;
22 }
23 }t[M];
24 void solve( int m)
25 {
26 int tem = t[m].child;
27 while (tem)
28 {
29 solve(tem);
30 t[m].vis += t[tem].novis;
31 t[m].novis += t[tem].maxx();
32 tem = t[tem].brother;
33 }
34 }
35 int main()
36 {
37 int n;
38 cin >> n;
39 for ( int i = 1 ;i <= n;i ++ )
40 {
41 t[i].init();
42 cin >> t[i].vis;
43 }
44 int a,b;
45 while (cin >> a >> b && a + b)
46 {
47 t[a].father = b;
48 t[a].brother = t[b].child;
49 t[b].child = a;
50 }
51 int i;
52 for (i = 1 ;i <= n;i ++ )
53 {
54 if ( ! t[i].father)
55 {
56 solve(i);
57 break ;
58 }
59 }
60 int ans = max(t[i].vis,t[i].novis);
61 cout << ans << endl;
62 return 0 ;
63 }
2
3 Problem: 2342 User: eth1
4 Memory: 456K Time: 94MS
5 Language: C ++ Result: Accepted
6 Source Code
7 #include < iostream >
8 #include < algorithm >
9 using namespace std;
10 const int M = 6001 ;
11 struct node
12 {
13 int father,brother,child;
14 int vis,novis;
15 int maxx()
16 {
17 return max(vis,novis);
18 }
19 void init()
20 {
21 father = brother = child = novis = 0 ;
22 }
23 }t[M];
24 void solve( int m)
25 {
26 int tem = t[m].child;
27 while (tem)
28 {
29 solve(tem);
30 t[m].vis += t[tem].novis;
31 t[m].novis += t[tem].maxx();
32 tem = t[tem].brother;
33 }
34 }
35 int main()
36 {
37 int n;
38 cin >> n;
39 for ( int i = 1 ;i <= n;i ++ )
40 {
41 t[i].init();
42 cin >> t[i].vis;
43 }
44 int a,b;
45 while (cin >> a >> b && a + b)
46 {
47 t[a].father = b;
48 t[a].brother = t[b].child;
49 t[b].child = a;
50 }
51 int i;
52 for (i = 1 ;i <= n;i ++ )
53 {
54 if ( ! t[i].father)
55 {
56 solve(i);
57 break ;
58 }
59 }
60 int ans = max(t[i].vis,t[i].novis);
61 cout << ans << endl;
62 return 0 ;
63 }