P1122 最大子树和

\(\color{#0066ff}{ 题目描述 }\)

小明对数学饱有兴趣,并且是个勤奋好学的学生,总是在课后留在教室向老师请教一些问题。一天他早晨骑车去上课,路上见到一个老伯正在修剪花花草草,顿时想到了一个有关修剪花卉的问题。于是当日课后,小明就向老师提出了这个问题:

一株奇怪的花卉,上面共连有\(N\)朵花,共有\(N-1\)条枝干将花儿连在一起,并且未修剪时每朵花都不是孤立的。每朵花都有一个“美丽指数”,该数越大说明这朵花越漂亮,也有“美丽指数”为负数的,说明这朵花看着都让人恶心。所谓“修剪”,意为:去掉其中的一条枝条,这样一株花就成了两株,扔掉其中一株。经过一系列“修剪“之后,还剩下最后一株花(也可能是一朵)。老师的任务就是:通过一系列“修剪”(也可以什么“修剪”都不进行),使剩下的那株(那朵)花卉上所有花朵的“美丽指数”之和最大。

老师想了一会儿,给出了正解。小明见问题被轻易攻破,相当不爽,于是又拿来问你。

\(\color{#0066ff}{输入格式}\)

第一行一个整数\(N(1 ≤ N ≤ 16000)\)。表示原始的那株花卉上共\(N\)朵花。

第二行有\(N\)个整数,第\(I\)个整数表示第\(I\)朵花的美丽指数。

接下来\(N-1\)行每行两个整数\(a,b\),表示存在一条连接第\(a\) 朵花和第\(b\)朵花的枝条。

\(\color{#0066ff}{输出格式}\)

一个数,表示一系列“修剪”之后所能得到的“美丽指数”之和的最大值。保证绝对值不超过2147483647

\(\color{#0066ff}{输入样例}\)

7
-1 -1 -1 1 1 1 0
1 4
2 5
3 6
4 7
5 7
6 7

\(\color{#0066ff}{输出样例}\)

3

\(\color{#0066ff}{数据范围与提示}\)

对于\(60\%\)的数据,有\(N\leq 1000\)

对于\(100\%\)的数据,有\(N\leq 16000\)

\(\color{#0066ff}{ 题解 }\)

一个普通的最大子段和,只不过放到了树上qwq

以f[i]代表以i为根的子树的最大子树和(强制选i)

子树优就选,ans根所有f取max

#include<bits/stdc++.h>
#define LL long long
LL in() {
	char ch; LL x = 0, f = 1;
	while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
	for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
	return x * f;
}
struct node {
	int to;
	node *nxt;
	node(int to = 0, node *nxt = NULL): to(to), nxt(nxt) {}
	void *operator new (size_t) {
		static node *S = NULL, *T = NULL;
		return (S == T) && (T = (S = new node[1024]) + 1024), S++;
	}
};
const int maxn = 2e4;
node *head[maxn];
int f[maxn], val[maxn];
int n;
int ans = -0x7fffffff;
void add(int from, int to) {
	head[from] = new node(to, head[from]);
}
void dfs(int x, int fa) {
	f[x] = val[x];
	for(node *i = head[x]; i; i = i->nxt) {
		if(i->to == fa) continue;
		dfs(i->to, x);
		if(f[i->to] >= 0) f[x] += f[i->to];
	}
	ans = std::max(ans, f[x]);
}
int main() {
	n = in();
	for(int i = 1; i <= n; i++) val[i] = in();
	int x, y;
	for(int i = 1; i < n; i++) x = in(), y = in(), add(x, y), add(y, x);
	dfs(1, 0);
	printf("%d\n", ans);
	return 0;
}
posted @ 2019-01-08 11:27  olinr  阅读(189)  评论(0编辑  收藏  举报