LG2996 「USACO10NOV」Visiting Cows

问题描述

LG2996


题解

和没有上司的舞会双倍经验?


(mathrm{Code})

#include<bits/stdc++.h>
using namespace std;

template <typename Tp>
void read(Tp &x){
	x=0;char ch=1;int fh;
	while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
	if(ch=='-'){fh=-1;ch=getchar();	}
	else fh=1;
	while(ch>='0'&&ch<='9')	x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
	x*=fh;
}

const int maxn=50007;
int n;
int Head[maxn],to[maxn<<1],Next[maxn<<1],tot;

void add(int x,int y){
	to[++tot]=y,Next[tot]=Head[x],Head[x]=tot;
}

int opt[maxn][2];

void dp(int x,int f){
	opt[x][0]=0,opt[x][1]=1;
	for(int i=Head[x];i;i=Next[i]){
		int y=to[i];
		if(y==f) continue;
		dp(y,x);
		opt[x][0]+=max(opt[y][1],opt[y][0]);
		opt[x][1]+=opt[y][0];
	}
}

int main(){
	read(n);
	for(int i=1,x,y;i<n;i++){
		read(x);read(y);
		add(x,y);add(y,x);
	}
	dp(1,0);
	printf("%d
",max(opt[1][0],opt[1][1]));
	return 0;
}
原文地址:https://www.cnblogs.com/liubainian/p/11832031.html