Luo Gu -1352 no party boss

Title Description
a university has N employees, numbered 1 ~ N. There are dependencies between them, that is their direct supervisor relationship is like a tree rooted to the principal, the parent node is the child node. Now there is the anniversary banquet, invited to a banquet every employee will increase a certain happiness index Ri, but then, if your boss to attend a staff party, then the staff would in any case would not come to the ball. Therefore, you programmed computing, which allows staff to invite the greatest happiness index, find the greatest happiness index.
Input Output Format
Input format:
The first line of an integer N. (1 <= N <= 6000 )
Next row N, i + 1-row number represents happiness index Ri i staff. (-128 <= Ri <= 127 )
the next N-1 lines, each pair of input integer L, K. L represents K is the direct supervisor.
The last line of input 00
output formats:
Output greatest happiness index.

Sample Input Output
Input Sample # 1:
. 7
1
1
1
1
1
1
1
1. 3
2. 3
. 6. 4
. 7. 4
. 4. 5
. 3. 5
0 0

Output Sample # 1:
5

Explanation: simple tree d p dp , provided d p [ r O O t ] [ 0 / 1 ] dp[root][0/1] represented by the value of the root node or not, then d p [ r O O t ] [ 0 ] = s O n m a x ( d p [ s O n ] [ 1 ] , d p [ s O n ] [ 0 ] ) , dp[root][0]=\sum_{son}max(dp[son][1],dp[son][0]), d p [ r o o t ] [ 1 ] = s o n d p [ s o n ] [ 0 ] dp[root][1]=\sum_{son}dp[son][0] maximum direct output statistical finished like a root

#include<iostream>
#define N 6006
using namespace std;
int head[N]={0};
int nex[N]={0};
int to[N]={0};
int tot=0;
int V[N]={0};
int du[N]={0};
int root=0;
int n=0;
int ret=0;
int dp[N][2]={0};
void add(int x,int y){
    tot++;
    nex[tot]=head[x];to[tot]=y;
    head[x]=tot;
}
void dfs(int u){
    int sum0=0;
    int sum1=0;
    for(int i=head[u];i;i=nex[i]){
        int v=to[i];
        dfs(v);
        sum1+=dp[v][0];
        sum0+=max(dp[v][0],dp[v][1]);
    }
    dp[u][1]=sum1+V[u];
    dp[u][0]=sum0;
}
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>V[i];
    for(int i=1,x,y;1;i++){
        cin>>x>>y;
        if(x+y==0) break;
        add(y,x);du[x]++;
    }
    for(int i=1;i<=n;i++){
        if(!du[i]) ret=i;
    }
    dfs(ret);
    cout<<max(dp[ret][0],dp[ret][1])<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/mkopvec/article/details/91949798