HDU ACM Anniversary party(树形DP)
http://acm.hdu.edu.cn/showproblem.php?pid=1520
1 #include <iostream> 2 using namespace std; 3 const int maxn = 6000 + 10; 4 struct Node{ 5 int not;//表示不取时的价值 6 int attend;//表示取时的价值 7 int child; 8 int brother; 9 int father; 10 }Tree[maxn]; 11 int d[maxn]; 12 int DP[maxn][2]; 13 int n; 14 void Init(){ 15 memset(d,0,sizeof(d)); 16 memset(Tree,0,sizeof(Tree)); 17 memset(DP,0,sizeof(DP)); 18 } 19 void BulidTree(){ 20 int i; 21 int x=1,y=1; 22 for(i=1;i<=n;i++){ 23 cin>>Tree[i].attend; 24 } 25 while(cin>>x>>y,x+y){//表示y是x的上司 26 Tree[x].father = y; 27 if(d[y] == 0){ 28 Tree[y].child = x; 29 } 30 else{ 31 Tree[d[y]].brother = x; 32 } 33 d[y] = x; 34 } 35 } 36 void TreeDP(int o){ 37 int child = Tree[o].child; 38 while(child != 0){ 39 TreeDP(child); 40 Tree[o].attend += Tree[child].not; 41 Tree[o].not += max(Tree[child].not,Tree[child].attend); 42 child = Tree[child].brother;//由于使用左儿子,右兄弟的师兄。 43 //遍历儿子的所有兄弟即遍历所有真正的儿子。 44 } 45 } 46 int main(){ 47 //freopen("out.txt","w",stdout); 48 //freopen("data.in","r",stdin); 49 while(cin>>n){ 50 Init(); 51 BulidTree(); 52 int i; 53 for(i=1;i<=n;i++){ 54 if(Tree[i].father == 0){ 55 TreeDP(i); 56 cout<<max(Tree[i].attend,Tree[i].not)<<endl; 57 } 58 } 59 } 60 61 } 62 /* 63 7 64 1 65 1 66 1 67 1 68 1 69 1 70 1 71 1 3 72 2 3 73 6 4 74 7 4 75 4 5 76 3 5 77 0 0 78 */