【BZOJ】2060: [Usaco2010 Nov]Visiting Cows 拜访奶牛

【算法】树形DP

【题解】没有上司的舞会?233

f[x][0]=∑max(f[v][0],f[v][1])

f[x][1]=(∑f[v][0])+1

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=50010;

struct edge{int v,from;}e[maxn*2];
int first[maxn],n,f[maxn][2],tot=0;

void insert(int u,int v){tot++;e[tot].v=v;e[tot].from=first[u];first[u]=tot;}
void dfs(int x,int fa){
    f[x][0]=0;f[x][1]=1;
    for(int i=first[x];i;i=e[i].from)if(e[i].v!=fa){
        dfs(e[i].v,x);
        f[x][0]+=max(f[e[i].v][0],f[e[i].v][1]);
        f[x][1]+=f[e[i].v][0];
    }
}
int main(){
    scanf("%d",&n);
    int u,v;
    for(int i=1;i<n;i++){
        scanf("%d%d",&u,&v);
        insert(u,v);insert(v,u);
    }
    dfs(1,0);
    printf("%d",max(f[1][0],f[1][1]));
    return 0;
}
View Code

 

posted @ 2017-09-26 16:09  ONION_CYC  阅读(190)  评论(0编辑  收藏  举报