题目描述:
143. Long Live the Queen
time limit per test: 0.5 sec.
memory limit per test: 4096 KB
The Queen of Bytelandis very loved by her people. In order to show her their love, the Bytelandershave decided to conquer a new country which will be named according tothe queen's name. This new country contains N towns. The towns areconnected by bidirectional roads and there is exactly ONE path betweenany two towns, walking on the country's roads. For each town, the profitit brings to the owner is known. Although the Bytelanders love their queenvery much, they don't want to conquer all the N towns for her. Theywill be satisfied with a non-empty subset of these towns, with the following2properties: there exists a path from every town in the subset to everyother town in the subset walking only through towns in the subset and theprofit of the subset is maximum. The profit of a subset of theNtowns is equal to the sum of the profits of the towns which belong to thesubset. Your task is to find the maximum profit the Bytelanders may get.
Input
The first line ofinput will contain the number of towns N (1<=N<=16 000). Thesecond line will contain N integers: the profits for each town,from 1 to N. Each profit is an integer number between -1000and 1000. The next N-1 lines describe the roads: each linecontains 2 integer numbers a and b, separated by blanks,denoting two different towns between which there exists a road.
Output
The output shouldcontain 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
题意就是给你一棵树,(m=n-1) 然后求出某个之树,其权值最大,树dp
dp[u] 表示 以u为根的之树的最大权值(包含u)
那么 dp[u]= sum[dp[v]] +w[u] 其中v是u的儿子,且 dp[v]>0;
WA#1 把ans初始化成0了,傻
RE#1 数组开小了,郁闷,为什么是16000呢,一般不是10000吗? 好吧,我承认我是傻。
贴代码开心:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>
#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define FOR(a,b) for(int a=1;a<=(b);(a)++)
using namespace std;
int const nMax = 16010;
int const base = 10;
typedef int LL;
typedef pair<LL,LL> pij;
// std::ios::sync_with_stdio(false);
int dp[nMax];
int w[nMax],vis[nMax];
vector<int> adj[nMax];
int n;
int ans;
void dfs(int u)
{
dp[u]=w[u];
vis[u]=1;
int v;
for(int i=0;i<adj[u].size();i++)if(!vis[v=adj[u][i]]){
dfs(v);
if(dp[v]>0)dp[u]+=dp[v];
}
if(dp[u]>ans)ans=dp[u];
return ;
}
int main(){
scanf("%d",&n);
FOR(i,n)adj[i].clear(),scanf("%d",&w[i]);
int u,v;
FOR(i,n-1){
scanf("%d%d",&u,&v);
adj[u].push_back(v);
adj[v].push_back(u);
}
ans=-inf;
CLR(vis,0);
dfs(1);
printf("%d\n",ans);
return 0;
}