sgu 143 Long live the Queen 简单树形dp

本文介绍了一道名为“Long Live the Queen”的树形DP题目解析,目标是在一棵树中选择一个连通子图,使得节点权值之和最大化。通过定义状态f[i]来表示以节点i为根的子树中的最大权值之和,并给出了实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// sgu 143  Long live the Queen 简单树形dp
//
// 题意:在树上选一个连通字图,使得节点的权值之和最大
// f[i] 表示以该节点为根的字图权值之和的最大值
// 则有 f[i] = w[i] + sigma(max(0,f[j])) i是j的父节点
// 最后在所有的f中挑个最大值就是答案。。。。


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define ceil(a,b) (((a)+(b)-1)/(b))
#define endl '\n'
#define gcd __gcd
#define highbit(x) (1ull<<(63-__builtin_clzll(x)))
#define popcount __builtin_popcountll
typedef long long ll;
using namespace std;
const int mod = 1000000007;
const long double pi = acos(-1.l);

template<class t> inline t lcm(const t& a, const t& b) { return a/gcd(a, b)*b; }
template<class t> inline t lowbit(const t& x) { return x&-x; }
template<class t> inline t maximize(t& a, const t& b) { return a=a<b?b:a; }
template<class t> inline t minimize(t& a, const t& b) { return a=a<b?a:b; }

const int maxn = 38900;
int w[maxn];
//int p[maxn];
vector<int> v[maxn];
bool vis[maxn];
int f[maxn];
int n;
struct node {
	int to;
	int next;
}edges[maxn];
int num;
int head[maxn/2];
void add_edge(int u,int v){
	edges[num].to = v;
	edges[num].next = head[u];
	head[u] = num++;
	
}
int dfs(int u,int fa){
	vis[u] = true;
	f[u] = w[u];
	for (int i=head[u];i!=-1;i=edges[i].next){
		int x = edges[i].to;
		
		if (!vis[x]){
			f[u] += max(0,dfs(x,u));
		}
	}
	
	return f[u];
}

void print(){
	for (int i=1;i<=n;i++)
		cout << f[i] << endl;
}
void init(){
	for (int i=1;i<=n;i++){
		scanf("%d",&w[i]);
	//	f[i] = w[i];
	}
	memset(head,-1,sizeof(head));
	num = 0;
	int a,b;
	for (int i=1;i<=n-1;i++){
		scanf("%d%d",&a,&b);
		add_edge(a,b);
		add_edge(b,a);
	}
	memset(vis,0,sizeof(vis));
	dfs(1,-1);
	int ans = f[1];
	for (int i=2;i<=n;i++)
		ans = max(ans,f[i]);
	printf("%d",ans);
	//print();
}


int main() {
	//freopen("g:\\code\\1.txt","r",stdin);
	scanf("%d",&n);
	init();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值