HIT2954PD EERT题解动态规划DP

http://acm.hit.edu.cn/judge/show.php?Proid=2954&Contestid=0

PD EERT

 

Time limit: 1sec. Submitted: 82
Memory limit: 64M Accepted: 35
Source: PerfectCai&Xnozero

Description

Maybe you have learned the data structure -- Tree.

Now there is a tree, which has n (1 ≤ n ≤ 1000) nodes(numbered from 1 to n), each node has a value c (-100 ≤ c ≤ 100).

Can you find a subtree of this tree, which has the maximum value.

InputThere will be several test cases. The first line of each case will contain a single positive integer n giving the number of nodes. The second line will contain n integers, giving the value of each node(from node 1 to node n). Then followed n-1 lines, each line has two numbers a and b, means there is an edge between a and b.

OutputFor each case, output one integer, the maximum value.

Sample Input

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

Sample Output2

题目倒过来是TREE DP
很简单的树形dp
状态:
d[i]第i个结点的子树最大值

 

状态转移方程:

d[i]=max(0,a[i])叶子结点

d[i]=max(0,a[i],a[i]+dfs(i))

dfs(i)表示i的子树的最大值

 

代码:

//http://acm.hit.edu.cn/judge/show.php?Proid=101370 #include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; int dp[1005],a[1005],n; vector<int> v[1005]; int dfs(int x) { if(dp[x]!=-1)return dp[x]; int i,t,len=v[x].size(); if(!len) return max(0,a[x]); for(t=i=0;i<len;i++) t+=dfs(v[x][i]); dp[x]=max(a[x],a[x]+t); dp[x]=max(0,dp[x]); return dp[x]; } int main() { while(scanf("%d",&n)==1) { int i,j,k; memset(dp,-1,sizeof(dp)); for(i=1;i<=n;i++) v[i].clear(); for(i=1;i<=n;i++) scanf("%d",a+i); for(i=1;i<n;i++) { scanf("%d%d",&j,&k); v[j].push_back(k); } dfs(1); printf("%d/n",dp[1]); } }

 

你可能感兴趣的:(tree,Integer,each,output,Numbers,structure)