SGU143 Long Live the Queen 树形DP

求一棵树中的权值最大的联通分量。简单TREE DP

143. Long Live the Queen

time limit per test: 0.5 sec. 
memory limit per test: 4096 KB

The Queen of Byteland is very loved by her people. In order to show her their love, the Bytelanders have decided to conquer a new country which will be named according to the queen's name. This new country contains N towns. The towns are connected by bidirectional roads and there is exactly ONE path between any two towns, walking on the country's roads. For each town, the profit it brings to the owner is known. Although the Bytelanders love their queen very much, they don't want to conquer all the N towns for her. They will be satisfied with a non-empty subset of these towns, with the following 2 properties: there exists a path from every town in the subset to every other town in the subset walking only through towns in the subset and the profit of the subset is maximum. The profit of a subset of the N towns is equal to the sum of the profits of the towns which belong to the subset. Your task is to find the maximum profit the Bytelanders may get.

Input

The first line of input will contain the number of towns N (1<=N<=16 000). The second line will contain N integers: the profits for each town, from 1 to N. Each profit is an integer number between -1000 and 1000. The nextN-1 lines describe the roads: each line contains 2 integer numbers a and b, separated by blanks, denoting two different towns between which there exists a road.

Output

The output should contain one integer number: the maximum profit the Bytelanders may get.

Sample Input

5
-1 1 3 1 -1
4 1
1 3
1 2
4 5

Sample Output

4

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

#define MAXN 16100
#define INF 0x3f3f3f3f

int dp[MAXN],w[MAXN];
int head[MAXN],n;
int next[MAXN*2],v[MAXN*2],en;
bool vis[MAXN];

void add(int a,int b)
{
    v[en]=b;next[en]=head[a];head[a]=en++;
    v[en]=a;next[en]=head[b];head[b]=en++;
}

void dfs(int u)
{
    vis[u]=1;dp[u]=0;
    for(int i=head[u];i!=-1;i=next[i]) if(!vis[v[i]])
        dfs(v[i]),dp[u]=dp[u]+max(0,dp[v[i]]);
    dp[u]+=w[u];
}

int main()
{
    //while(~scanf("%d",&n))
    //{
    scanf("%d",&n);
        for(int i=1;i<=n;i++) scanf("%d",&w[i]);
        int u,v,ans=0;;
        memset(head,-1,sizeof(head));en=0;
        for(int i=0;i<n-1;i++)
        {
            scanf("%d%d",&u,&v);
            add(u,v);
        }
        memset(vis,0,sizeof(vis));
        dfs(1);
        ans=-INF;
        for(int i=1;i<=n;i++) ans=max(ans,dp[i]);
        printf("%d\n",ans);
    //}
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值