POJ 2342 Anniversary party ~~Tree Dp

来源:互联网 发布:python 哪方面的私活多 编辑:程序博客网 时间:2024/05/20 06:49
/*【题意】公司有n个人,每个人有价值vi,有一天举办年会,每个人都可以参加,但有严格的等级制度,参加活动时,不能同时出现a和a的上司,问如何才能使总和最大。【分析】每个人只有去和不去两种状态,设f[i][0]和f[i][1]分别表示第i个人不参加和参加年会,获得的总的最大价值。则状态转移方程为:f[i][1] += f[j][0],f[i][0] += max{f[j][0],f[j][1]};其中j为i的孩子节点。这样,从根节点root进行dfs,最后结果为max{f[root][0],f[root][1]}。*/#include<iostream>#include<cstdio>#include<cstring>#include<vector>const int maxn=6000+5;using namespace std;struct node{int fa;vector<int>ch;}a[maxn];int f[maxn][2],p[maxn];void dfs(int x){p[x]=1;int s=a[x].ch.size();for(int i=0;i<s;i++){int k=a[x].ch[i];if(!p[k]){dfs(k);f[x][1]+=f[k][0];f[x][0]+=max(f[k][0],f[k][1]);}}}int main(){freopen("test.in","r",stdin);freopen("test.out","w",stdout);int i,j,k,m,n,x,y,root=1;cin>>n;for(i=1;i<=n;i++)scanf("%d",&f[i][1]);while(scanf("%d%d",&x,&y),x+y>0){a[x].fa=y;a[y].ch.push_back(x);}for(i=1;i<=n;i++)if(a[i].fa==0){root=i;break;}dfs(root);printf("%d\n",max(f[root][0],f[root][1]));return 0;}