codeforces 982C Cut 'em all! (dfs)

题目链接:https://codeforces.com/problemset/problem/982/C

even是偶数的意思。。。
原本以为的题意是:删边后剩下的联通块大小相等(不会做

做法

贪心,如果子树大小是偶数,就删边,剩下的部分也必定是偶数
最后判断一下整棵树是否是奇数

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 100010;

int n,ans;
int dp[maxn][2]; // i 的子树,删/不删 

int h[maxn],cnt = 0;
struct E{
	int next,to;
}e[maxn * 2];
void add(int u,int v){
	e[++cnt].to = v;
	e[cnt].next = h[u];
	h[u] = cnt;
}

int sz[maxn] ;

void dfs(int u,int par){
	sz[u] = 1;
	for(int i=h[u];i!=-1;i=e[i].next){
		int v = e[i].to;
		if(v==par) continue;
		dfs(v,u);
		sz[u] += sz[v];
	}
	if(sz[u] % 2 == 0){
		++ans;
	}
}

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	ans = 0;
	memset(h,-1,sizeof(h));
	n = read();
	
	int u,v;
	for(int i=1;i<=n-1;i++){
		u = read(),v = read();
		add(u,v),add(v,u);
	}
	
	dfs(1,0);
	
	if(sz[1] % 2 == 1){
		printf("-1\n");
	}else{
		printf("%d\n",ans-1);
	}
	
	return 0;
}
posted @ 2020-10-17 11:44  Tartarus_li  阅读(92)  评论(0编辑  收藏  举报