题意:
思路:建上司与下属的树图。
每个结点分取与不取的状态,则有dp[node][0]表示不取,dp[node][1]为取
则dp[faher][1]=sum(dp[child][0])+value[fahter];
dp[father][0]=sum(max(dp[child][0],dp[child][1]));
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
const int MAXN=6000;
int power[MAXN+10];
//int f[MAXN*(MAXN-1)/2+10];
int f[MAXN+10];
int n;
bool visit[MAXN];
int result[MAXN][2];
void tree_dp(int node)
{
int i;
for(i=1;i<=n;i++)
{
if(visit[i]==false&&f[i]==node)
{
tree_dp(i);
result[node][1]+=result[i][0]+power[i];
result[node][0]+=max(result[i][0],result[i][1]);
}
}
return;
}
int main()
{
int child,father;
int root;
int i;
//while(scanf("%d",&n)!=EOF)
scanf("%d",&n);
{
memset(visit,0,sizeof(visit));
memset(result,0,sizeof(result));
root=0;
for(i=1;i<=n;i++)
{
scanf("%d",&power[i]);
}
memset(f,0,sizeof(f));
while(scanf("%d %d",&child,&father)&&child&&father)
{
f[child]=father;
if(child==root)
{
root=father;
}
}
}
tree_dp(root);
printf("%d/n",max(result[root][0],result[root][1]));
return 0;
}
附题目:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1978 | Accepted: 1072 |
Description
Input
Output
Sample Input
7 1 1 1 1 1 1 1 1 3 2 3 6 4 7 4 4 5 3 5 0 0
Sample Output
5