题目大意:n个人,接下来n行是n个人的价值,再接下来n行给出l,k说的是l的上司是k,这里注意l与k是不能同时出现的
解题思路:用dp来记录最大价值,出发点为当前根节点是否选择,从根节点进行dfs
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <list>
#include <set>
using namespace std;
const int maxn = 6000+10;
int fat[maxn],vis[maxn],dp[maxn][2],n;
void dfs(int node)
{
vis[node] = 1;
for(int i = 1; i <= n; i++)
{
if(!vis[i] && fat[i] == node)
{
dfs(i);
dp[node][0] += max(dp[i][1],dp[i][0]);
dp[node][1] += dp[i][0];
}
}
}
int main()
{
int x,l,k;
while(scanf("%d",&n) != EOF)
{
for(int i = 1; i <= n; i++)
{
scanf("%d",&x);
dp[i][1] = x;
}
memset(vis,0,sizeof(vis));
int root = 0;
while(scanf("%d%d",&l,&k) != EOF)
{
if(!(l+k)) break;
fat[l] = k;
root = k;
}
while(fat[root] != root)
fat[root] = root;
dfs(root);
printf("%d\n",max(dp[root][0],dp[root][1]));
}
return 0;
}