Codeforces Round #484 (Div. 2)Cut 'em all!(dfs)

题目链接
题意:给你一棵树,让你尽可能删除多的边使得剩余所有的联通组件都是偶数大小。
思路:考虑dfs,从1出发,若当前节点的子节点和自己的数目是偶数,说明当前节点和父亲节点的边是可以删除的,答案+1,因为最开始的节点没有父节点,所以最后答案-1

#include<bits/stdc++.h>

#define LL long long
#define fi first
#define se second
#define mp make_pair
#define pb push_back

using namespace std;

LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
LL lcm(LL a,LL b){return a/gcd(a,b)*b;}
LL powmod(LL a,LL b,LL MOD){LL ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
const int N = 2e5 +11;
int n;
vector<int>v[N];
int ans=0;
int dfs(int now,int pre){
	int su=1;
	for(int k:v[now]){
		if(k==pre)continue;
		su+=dfs(k,now);
	}
	if(su%2==0)ans++;
	return su;
}
int main(){
	ios::sync_with_stdio(false);
	cin>>n;
	if(n&1)return cout<<-1,0;
	for(int i=2;i<=n;i++){
		int s,t;
		cin>>s>>t;
		v[s].pb(t);
		v[t].pb(s);
	}
	dfs(1,0);
	cout<<ans-1;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40655981/article/details/89329173