码迷,mamicode.com
首页 > Windows程序 > 详细

AcWing 285. 没有上司的舞会

时间:2019-11-21 17:01:50      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:bool   print   pre   string   mem   sizeof   class   bsp   algo   

//f[u][0]是所有以u为根的子树中选择,并且不选u这个点的方案
//f[u][1]是所有以u为根的子树中选择,并且  选u这个点的方案
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 6010;
int n;
int h[N], e[N], ne[N], idx;
int happy[N];
int f[N][2];//两种状态
bool has_fa[N];
void add(int a, int b) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
void dfs(int u) {
    f[u][1] = happy[u];//选择这个点 
    for (int i = h[u]; i!=-1; i = ne[i]) {//枚举所有儿子 
        int j = e[i];
        dfs(j);
        f[u][1] += f[j][0];
        f[u][0] += max(f[j][0], f[j][1]);
    }
}
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++ ) scanf("%d", &happy[i]);
    memset(h, -1, sizeof h);
    for (int i = 0; i < n - 1; i ++ ) {
        int a, b;
        scanf("%d%d", &a, &b);
        add(b, a);
        has_fa[a] = true;//表示有爹,不是根节点
    }
    int root = 1;
    while (has_fa[root]) root ++ ;//找根节点
    dfs(root);
    printf("%d\n", max(f[root][0], f[root][1]));
    return 0;
}

 

 

AcWing 285. 没有上司的舞会

标签:bool   print   pre   string   mem   sizeof   class   bsp   algo   

原文地址:https://www.cnblogs.com/QingyuYYYYY/p/11906311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!