CF1592C Bakry and Partitioning


题目链接

知识点:dfs、树分块、异或、贪心

题意

将带点权值树按点分成不超过k个块且必须分块,使得每个块的异或和相等,求是否能够做到。

思路

两个块异或和相等则两个块异或和的异或为 0 0 0,不相等则记为 a n s ans ans,可再分其中一块,使分成的三块中两块异或和的异或为 0 0 0,另一块记为 S S S S S S的异或和为 a n s ans ans。推广到整棵树上就是 S S S的异或和 a n s ans ans为整棵树的异或和,将树分为异或和为 a n s ans ans的块即可。
整棵树的异或和为 0 0 0时,因为 0 = a n s ⊕ a n s 0=ans \oplus ans 0=ansans,类似可证块个数为偶数,必符合题意。不为 0 0 0时,连通块个数 > 3 > 3 >3时,可用 a n s ⊕ a n s ⊕ a n s = a n s ans \oplus ans \oplus ans=ans ansansans=ans化成 = 3 =3 =3,故分成 3 3 3块时符合题意,直接结束程序。
实现思路见代码。

代码(希望csdn出个代码折叠功能)

#include"cstdio"
#include"vector"
#include"bitset"
#include"algorithm"
#include"queue"
#include"map"
#include"iostream"

#define db(x) cout<<(#x)<<':'<<(x)<<endl;
#define ll long long
#define vec vector<ll>
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pii pair<ll,ll>
#define x first
#define y second
#define tinfo ll rt,ll l,ll r
#define sl rt<<1,l,mid
#define sr rt<<1|1,mid+1,r
#define mid (l+r>>1)
const ll mod=1e9+7;
const ll N=1e5+10;
using namespace std;

ll t,n,k;
ll arr[N];//i点的权值
vec graph[N];
ll ans;//思路中的ans
ll cutcnt;//当前块个数
//叶节点无分支,从叶节点开始分块
void dfs(ll now,ll fa) {
  if(cutcnt==3) return;
  for(int i=0; i<graph[now].size(); i++) {
    ll nxt=graph[now][i];
    if(nxt==fa) continue;
    //先dfs到叶节点再分块
    dfs(nxt,now);
    arr[now]^=arr[nxt];//子节点并到父节点上
  }
  //找到一个块
  if(arr[now]==ans) {
    arr[now]=0;//这个块找到后不能并到父节点上,子节点设为0对父节点无意义
    cutcnt++;
  }
}

void init() {
  cutcnt=ans=0;
  for(int i=1; i<=n; i++) graph[i].clear();
}

int main() {
  scanf("%lld",&t);
  while(t--) {
    scanf("%lld%lld",&n,&k);
    init();
    //计算整棵树的异或和
    for(int i=1; i<=n; i++) {
      scanf("%lld",&arr[i]);
      ans^=arr[i];
    }
    for(int i=1; i<=n-1; i++) {
      ll u,v;
      scanf("%lld%lld",&u,&v);
      graph[u].pb(v);
      graph[v].pb(u);
    }
    //异或和为0
    if(ans==0) {
      puts("YES");
      continue;
    }
    //只能分成1个块
    if(k<3) {
      puts("NO");
      continue;
    }
    dfs(1,0);
    //只有一个块(未分块)
    if(cutcnt<=1)
      puts("NO");
    else puts("YES");
  }

  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值