Codeforces Round #746 (Div. 2) C. Bakry and Partitioning


给定一颗树,问是否能分成至少2个至多k个异或值都相同的连通分量
根据异或的性质,设最后的异或值为a,那么原先的值只能为a或0
当原先的值为0时,显然可行(x^x=0)
当原先的值为a时,只需要找到两个不同子树的的异或值为a即可行
#include<bits/stdc++.h>
using namespace std;
 
const int N = 2e5+10;
 
int a[N],cnt,r;
 
int dfs(int cur,int fa,int flag,vector<vector<int>>& tr){
	int t=a[cur];
	for(int i=0;i<tr[cur].size();i++){
		if(tr[cur][i]==fa) continue;
		int k=dfs(tr[cur][i],cur,flag,tr);
		t^=k;
		if(flag && k && !cnt){
			cnt++;
		}
		else if(k==r && !flag && cnt<2){
			cnt++;
			t^=k;
		}
	}
	return t;
}
 
int main(){
	int T;
	cin>>T;
	while(T--){
		cnt=0,r=0;
		int n,k;
		cin>>n>>k;
		for(int i=1;i<=n;i++){
			cin>>a[i];
			r^=a[i];
		} 
		vector<vector<int>> tr(n+1);
		for(int i=1;i<n;i++){
			int x,y;
			cin>>x>>y;
			tr[x].push_back(y);
			tr[y].push_back(x);
		}
		if(r==0) dfs(1,0,1,tr);
		else dfs(1,0,0,tr);
		if(r==0 && cnt==1) puts("YES");
		else if(r!=0 && cnt==2 && cnt<=k-1) puts("YES");
		else puts("NO");
	}
}

posted @ 2022-05-29 19:38  xhy666  阅读(59)  评论(0)    收藏  举报