P1352 没有上司的舞会(树形DP入门,自底向上更新)

f [ u ] [ 1 ] 表示当前点 取,f [ u ] [ 0 ] 表示当前点 不取
则有状态转移方程:
f [ u ] [ 0 ] += max( f [ v ] [ 0 ] ,f [ v ] [ 1 ] ) ,v是u的儿子结点;
【比线性dp多了个子节点求和】
f [ u ] [ 1 ] += f [ v ] [ 0 ];

AC代码

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e4+5;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const LL maxn=1e18;
LL read()
{
    LL x=0,t=1;
    char ch=getchar();
    while(!isdigit(ch)){ if(ch=='-')t=-1; ch=getchar(); }
    while(isdigit(ch)){ x=10*x+ch-'0'; ch=getchar(); }
    return x*t;
}

struct edge
{
    int from,to,next;
    edge(){}
    edge(int ff,int tt,int nn)
    {
        from=ff; to=tt; next=nn;
    }
};
edge e[N<<1];
int f[N][2],a[N],head[N],in[N],tot;
void add(int from,int to)
{
    e[++tot]=edge(from,to,head[from] );
    head[from]=tot;
}
void dfs(int u)
{
    f[u][0]=0;
    f[u][1]=a[u];
    for(int i=head[u];i;i=e[i].next)
    {
        int v=e[i].to;
        dfs(v);
        f[u][0]+=max(f[v][0],f[v][1]);
        f[u][1]+=f[v][0];
    }
}
int main()
{
    int n=read();
    for(int i=1;i<=n;i++) a[i]=read();
    for(int i=1;i<n;i++)
    {
        int x=read(),y=read();
        add(y,x);
        in[x]++;
    }
    read();read();
    int root;
    for(int i=1;i<=n;i++)
        if(!in[i])
        {
            root=i;
            dfs(i);
            break;
        }
    printf("%d
",max(f[root][0],f[root][1] ) );
    return 0;
}
原文地址:https://www.cnblogs.com/DeepJay/p/12025200.html