南阳理工OJ 697 The Weight of Tree 树上的最大块

连接:http://acm.nyist.net/JudgeOnline/problem.php?pid=697

 

The Weight of Tree

时间限制: 3000 ms  |  内存限制: 65535 KB
难度: 4
 
描述
456 has a tree of n nodes, each node is assigned with an integer number. Now 456 wants to select a subtree, such that the sum of all integers on the nodes of the subtree is maxmized. Can you help him? 
 
输入
On the first line of the input is an integer T, and then T cases follows. Each case begins with a positive integer n(1 <= n <= 10^5), then n numbers Wi(-1000 <= Wi <= 1000),Wi for the number on the ith node. Then n - 1 lines follows, each line contains two numbers a, b(1 <= a, b <= n)indicate that there is a edge between node a and b.
输出
For each test case, output one integer on a line, the maximized sum can be achieved by selecting a subtree. 
样例输入
3
1
5
2
5 -5
1 2
5
-2 -3 7 -1 4
1 2
2 3
3 4
2 5
样例输出
5
5
8

 

#include<cstdio>
#include<cstring>
#include<vector>
#define inf 1<<30
using namespace std;
vector<int>link[100010];
bool mask[100010];
int w[100010];
int maxn,n;
int dfs(int a)
{
       int term,res=0;
       mask[a]=1;
       for(int i=0;i<link[a].size();i++)if(mask[link[a][i]]==0)
       {
              term=dfs(link[a][i]);
              if(term<0)continue;
              res+=term;
       }
       if(res+w[a]>maxn)maxn=res+w[a];
       return res+w[a];
}
int main()
{
     //  freopen("in.txt","r",stdin);
	int T;
	scanf("%d",&T);
	while(T--)
	{
	       memset(mask,0,sizeof(mask));
	       scanf("%d",&n);
	       for(int i=1;i<=n;i++)link[i].clear();
	       for(int i=1;i<=n;i++)scanf("%d",&w[i]);
	       for(int i=1;i<n;i++)
	       {
	              int a,b;
	              scanf("%d%d",&a,&b);
	              link[a].push_back(b);
	              link[b].push_back(a);
	       }
	       maxn=-inf;
	       dfs(1);
	       printf("%d\n",maxn);
	}
	return 0;
}

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值