Anniversary party
Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 9137 Accepted Submission (s): 3917
Problem Descriptionthere is going to be a party to celebrate the 80-th anniversary of the Ural state University. The University has a hierarchical structure of employees. It means the supervisor relation forms a tree rooted at the Rector v. E. Tretyakov. In order to make the party funny for every one, the rector does not want both a employee and his or her immediate supervi Sor to is present. The personnel office has evaluated conviviality of all employee, so everyone had some number (rating) attached to him or Her. Your task is to make a list of guests with the maximal possible sum of guests ' conviviality ratings.
Inputemployees is numbered from 1 to N. A first line of input contains a number n. 1 <= n <= 6 000. Each of the subsequent N lines contains the conviviality rating of the corresponding employee. Conviviality rating is an integer number in a range from-128 to 127. After the go T lines that describe a supervisor relation tree. Each line of the tree specification has the form:
L K
It means that the k-th employee was an immediate supervisor of the L-th employee. Input is ended with the line
0 0
Outputoutput should contain the maximal sum of guests ' ratings.
Sample Input711111111 32 36 47 44 53 50 0
Sample Output5 tree DP and linear DP are similar. DFS a bit.
#include <iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<vector>using namespacestd;intN;inthappy[6005];vector<int> son[6005];intdp[6005][3];intvis[6005];voidDfsintNow ) {dp[now][1] =Happy[now]; dp[now][0] =0; for(intI=0; I<son[now].size (); i++) { intNEX =Son[now][i]; DFS (NEX); dp[now][1] + = dp[nex][0]; dp[now][0] + = max (dp[nex][0],dp[nex][1]); }}intMain () { while(SCANF ("%d", &n)!=eof&&N) {memset (DP,0,sizeof(DP)); memset (Vis,0,sizeof(VIS)); for(intI=1; i<=n;i++) {scanf ("%d",&Happy[i]); } intl,k; while(1) {scanf ("%d%d",&l,&k); if(l==0&&k==0) Break; Son[k].push_back (l); VIS[L]=1; } intFather =0; for(intI=1; i<=n;i++) { if(!Vis[i]) {Father=i; Break; }} dfs (father); printf ("%d\n", Max (dp[father][0],dp[father][1])); for(intI=1; i<=n;i++) son[i].clear (); } return 0;}
HDU 1520 (tree-shaped DP)