NYOJ 679 The Weight of Tree 搜索+dp+邻接表

来源:互联网 发布:淘宝出售中的商品id 编辑:程序博客网 时间:2024/06/03 08:42

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. 
样例输入
31525 -51 25-2 -3 7 -1 41 22 33 42 5

样例输出

558
    从第一个点一直往下深搜,然后回溯,判断子节点的值是否大于0,如果大于0,父节点的值变为当前的值加上子节点的值。最后输出最大值即可。

#include<stdio.h>#include<string.h>#include<vector>#include<algorithm>#define N 100005using namespace std;vector<int> vec[N];int vis[N],dp[N],MAX;void dfs(int x){vis[x]=1;for(int i=0;i<vec[x].size();i++){int y=vec[x][i];if(vis[y])   continue;        dfs(y);        if(dp[y]>0)           dp[x]+=dp[y];MAX=max(dp[x],MAX);    }}int main(){int t,n,i,a,b;scanf("%d",&t);while(t--){memset(vis,0,sizeof(vis));memset(vec,0,sizeof(vec));scanf("%d",&n);MAX=-999999;for(i=1;i<=n;i++){scanf("%d",&dp[i]);MAX=max(dp[i],MAX);}for(i=1;i<n;i++){scanf("%d%d",&a,&b);vec[a].push_back(b);vec[b].push_back(a);}dfs(1);printf("%d\n",MAX);}return 0;}


原创粉丝点击