There 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 that 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 an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has 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.
L K
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line
0 0
7 1 1 1 1 1 1 1 1 3 2 3 6 4 7 4 4 5 3 5 0 0
5
题目大概:
在n个人之间有上司和下属的关系,其实就是树的父亲和孩子,每个人都有权值,孩子和父亲不能同时选择,找出最大的权值。
思路:
之前看过不少博客,这个题有很多做法。
其实这个题最开始是用的直接枚举法找的父亲的孩子是谁,但是超时了,就改为用vector存储父亲的孩子是谁,方便查找和计算,并且用了记忆化,减少用时。
dp[i][0]就是第i个人不被选择,dp[i][1]是第i个人被选择。
那么第i个人有两种情况,第i-1个人被选择的时候,第i个人一定不能选 ans+=dp[i][0];
第i-1个人不被选择的时候,第i个人可选可不选 ans+=max(dp[i][0],dp[i][1]);
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int t,root;
int dp[60002][2];
int a[6002];
int d[6002];
vector<int>f[6002];
int dfs(int x,int k)
{
int &ans=dp[x][k];
if(ans!=-1)return ans;
ans=0;
if(k)ans+=a[x];
for(int i=0;i<f[x].size();i++)
{
int j=f[x][i];
if(k) ans+=dfs(j,0);
else ans+=max(dfs(j,0),dfs(j,1));
}
return ans;
}
int main()
{
int q,w;
while(~scanf("%d",&t))
{
memset(dp,-1,sizeof(dp));
memset(a,0,sizeof(a));
for(int i=1;i<=t;i++)
{
scanf("%d",&a[i]);
f[i].clear();
}
int root=0;
while(scanf("%d%d",&q,&w)&&(q!=0&&w!=0))
{
f[w].push_back(q);
d[q]++;
}
for(int i=1;i<=t;i++)
{
if(d[i]==0)root=i;
}
printf("%d\n",max(dfs(root,0),dfs(root,1)));
}
return 0;
}