zoukankan      html  css  js  c++  java
  • hdu 1520 树形dp

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1520

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<iostream>
    #include<algorithm>
    #include<queue>
    #include<vector>
    using namespace std;
    const int maxn = 6050;
    const int maxe = 10000;
    const int INF = 0x3f3f3f;
    
    struct Edge{
        int u,v;
        int next;
        void assign(int u_,int v_,int next_){
            u = u_;    v = v_;   next = next_;
        }
    }tree[maxe];
    
    int head[maxn];
    int dp[maxn][2];
    int R[maxn];
    int vis[maxn];
    int cnt;
    int N,M;
    
    void addedge(int u,int v){
        tree[cnt].assign(u,v,head[u]);
        head[u] = cnt++;
    }
    void init(){
        cnt = 0;
        memset(dp,0,sizeof(dp));
        memset(head,-1,sizeof(head));
        memset(vis,0,sizeof(vis));
    }
    
    void dfs(int u,int fa){
        dp[u][1] = R[u];
        for(int i=head[u];i!=-1;i=tree[i].next){
            int v = tree[i].v;
            if(v == fa) continue;
            dfs(v,u);
            dp[u][1] += dp[v][0];
            dp[u][0] += max(dp[v][1],dp[v][0]);
        }
    }
    int main()
    {
        //freopen("E:\acm\input.txt","r",stdin);
    
        while(cin>>N){
            init();
            for(int i=1;i<=N;i++)    scanf("%d",&R[i]);
            int u,v;
            while(scanf("%d%d",&v,&u) && u+v){
                addedge(u,v);
                vis[v] = true;
            }
            int root;
            for(int i=1;i<=N;i++)    if(!vis[i])  { root = i; break; }
            memset(vis,0,sizeof(vis));
            dfs(root,-1);
            printf("%d
    ",max(dp[root][1],dp[root][0]));
        }
    
    }
    View Code
  • 相关阅读:
    Linux常用操作命令总结
    Centos7安装FastDFS教程
    Permutation Sequence
    Next Permutation
    Remove Element
    4Sum
    3Sum Closest
    3Sum
    Longest Consecutive Sequence
    Median of Two Sorted Arrays
  • 原文地址:https://www.cnblogs.com/acmdeweilai/p/3250520.html
Copyright © 2011-2022 走看看