码迷,mamicode.com
首页 > 其他好文 > 详细

sgu 143 Long live the Queen 简单树形dp

时间:2015-05-24 15:45:12      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:sgu 143   long live the queen   简单树形dp   

// 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;
}

sgu 143 Long live the Queen 简单树形dp

标签:sgu 143   long live the queen   简单树形dp   

原文地址:http://blog.csdn.net/timelimite/article/details/45952227

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!