今天算第一次看树形DP,网上找了资料,恰好有一个练习题,便仿着做了。方法其实比较简单,跟线性DP差不多,只是多了树的操作。
直接贴代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#define MAX 6001
using namespace std;
struct node{
struct node *first_child;
struct node *next_sibling;
int max_with;
int max_without;
}a[MAX];
void dp(struct node *node)
{
struct node *child=node->first_child;
while(child!=NULL)
{
dp(child);
node->max_with+=child->max_without;
node->max_without+=max(child->max_with,child->max_without);
child=child->next_sibling;
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
{
scanf("%d",&a[i].max_with);
a[i].first_child=a[i].next_sibling=NULL;
}
int root=(n-1)*n/2;
while(1)
{
int ita,itb;
scanf("%d%d",&ita,&itb);
if(ita+itb==0)
break;
ita--;
itb--;
a[ita].next_sibling=a[itb].first_child;
a[itb].first_child=a+ita;
root-=ita;
}
dp(a+root);
printf("%d\n",max(a[root].max_with,a[root].max_without));
}
return 0;
}