树形dp经典题目

P1352 没有上司的舞会

#include <bits/stdc++.h>
using namespace std;
int n, r[6010], l, k, root, fa[6010], f[6010][2], ans;	//k是l的上司 
vector<int> son[6010]; 
void dp(int x)
{
	f[x][0]=0;			//x不参加舞会
	f[x][1]=r[x]; 		//x参加舞会
	for(int i=0; i<son[x].size(); ++i){		
		int y=son[x][i];
		dp(y);
		f[x][0]+=max(f[y][0], f[y][1]);
		f[x][1]+=f[y][0];
	}
}
int main()
{
	scanf("%d", &n);
	for(int i=1; i<=n; ++i){
		scanf("%d", &r[i]);
	} 
	for(int i=1; i<=n-1; ++i){
		scanf("%d %d", &l, &k);		//k是l的上司
		fa[l]=k; 					//k是父亲结点 
		son[k].push_back(l);		//l是儿子结点 
	}
	//找根节点 
	for(int i=1; i<=n; ++i){
		if(!fa[i]){
			root=i;
			break;
		}
	} 
	dp(root);
	ans=max(f[root][0], f[root][1]);
	printf("%d", ans); 
	return 0;
}

P2015 二叉苹果树

P1273 有线电视网

P1040 [NOIP2003 提高组] 加分二叉树

P1122 最大子树和

P2014 [CTSC1997] 选课

P2585 [ZJOI2006]三色二叉树

P3047 [USACO12FEB]Nearby Cows G

P3698 [CQOI2017]小Q的棋盘

P5658 [CSP-S2019] 括号树

P2607 [ZJOI2008] 骑士

P3177 [HAOI2015] 树上染色

P4395 [BOI2003]Gem 气垫车

P4516 [JSOI2018] 潜入行动

猜你喜欢

转载自blog.csdn.net/u013313909/article/details/127941370