poj 2342树形dp板子题1

http://poj.org/problem?id=2342

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
inline int read(){
    int sum=0,x=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')
            x=0;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        sum=(sum<<1)+(sum<<3)+(ch^48),ch=getchar();
    }
    return x?sum:-sum;
}
inline void write(int x){
    if(x<0)
        putchar('-'),x=-x;
    if(x>9)
        write(x/10);
    putchar(x%10+'0');
}
int mi(int x,int y){
    return x<y?x:y;
}
int ma(int x,int y){
    return x>y?x:y;
}
const int M=6e3+3;
vector<int>g[M];
int f[M],dp[M][2];

void dfs(int u){
    for(int i=0;i<g[u].size();i++){
        int v=g[u][i];
        dfs(v);
        dp[u][0]+=ma(dp[v][0],dp[v][1]);
        dp[u][1]+=dp[v][0];
    }
}
int main(){
    int n=read();
    
    for(int i=1;i<=n;i++){
        dp[i][1]=read();
    }
    while(true){
        int x=read(),y=read();
        if(!x&&!y)
            break;
        g[y].push_back(x);
        f[x]=y;
    }
    int root=1;
    while(f[root]!=0)
        root=f[root];
    dfs(root);
    write(ma(dp[root][0],dp[root][1]));
    return 0;
}
View Code

 

posted @ 2019-06-01 22:35  starve_to_death  阅读(114)  评论(0编辑  收藏  举报