LuoGu P1352 没有上司的舞会

题目传送门
这可能是最简单的树形Dp了吧
对于每个人,要么他来,他的下属不来
要么他不来,他的下属爱来不来
于是设计状态:
f[i][0/1]表示以i为根的子树中最大能达到的快乐值(i这个人选或者不选)
然后一遍dfs一遍转移就好了

#include <iostream>
#include <cstdlib>
#include <cstdio>
#define max(a,b) (a>b?a:b)

using namespace std;

const int N=6e3+5;

struct edge{
	int to,next,pre;
}e[N];

int f[N][2],n,val[N],u,v,head[N],tot,ans=0;
bool had[N];

inline void build(int u,int v){
	e[++tot].next=head[u];e[tot].pre=u;
	head[u]=tot;e[tot].to=v;
	return ;
}

inline void work(int x){
	f[x][0]=0;f[x][1]=val[x];
	for(int i=head[x];i;i=e[i].next){
		int k=e[i].to;
		work(k);
		f[x][0]+=max(f[k][1],f[k][0]);
		f[x][1]+=f[k][0];
	}
	return ;
}

int main(){
	scanf("%d",&n);
	for(register int i=1;i<=n;++i) scanf("%d",&val[i]);
	do{
		scanf("%d%d",&u,&v);
		build(v,u);had[u]=true;
	}while(u!=0&&v!=0);
	for(int i=1;i<=n;++i) if(!had[i]) work(i);
	for(register int i=1;i<=n;++i) ans=max(ans,max(f[i][1],f[i][0]));
	printf("%d
",ans);
	return 0;
}
May you return with a young heart after years of fighting.
原文地址:https://www.cnblogs.com/Equinox-Flower/p/9630545.html