Long Live the Queen_树形dp

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ujn20161222/article/details/79947239

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 next N-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<bits/stdc++.h>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;

const int N=16000+10;
int p[N];
int d[N];
bool vis[N];
vector<int> v[N];


void dfs(int u){
    d[u]=p[u];
    vis[u]=true;
    for(int i=0;i<v[u].size();i++)
    if(!vis[v[u][i]]){
        dfs(v[u][i]);
        d[u]+=max(0,d[v[u][i]]);
    }
}


int main(){
    freopen("in.txt","r",stdin);
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>p[i];
    for(int j=1;j<n;j++){
        int x,y;
        cin>>x>>y;
        x--,y--;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    dfs(0);
    int mm=-1000000;
    for(int k=0;k<n;k++)
    if(d[k]>mm)
    mm=d[k];
    cout<<mm<<endl;
    fclose(stdin);
}



 
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页