Bakry and Partitioning
[link](Problem - C - Codeforces)
题意
给你一颗树,每个节点有一个权值ai,然后给你一个k,问你至少砍掉一条边,最多砍掉k-1条边,使得砍完以后所有的连通块的节点异或值相同。问你是否可以达到这种情况。
题解
首先如果整个树的异或和是0那就说明至少有两个连通块是一样的,所以一定可以,然后如果异或和不为零我们至少要砍成三个连通块,因此k至少要大于等于三,而且当你砍成五个的成立的时候,一定可以将其中两个合并,所以最终只需要判断是不是可以砍成三个相等连通块即可。总和是sum,只需要看是否可以找到两个子树的和也是sum即可。
直接dfs维护一下即可,假设当前这个子树的异或和是sum,那么他的父节点的异或和不能包含他,因为他已经被砍掉了。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#include <deque>
#include <sstream>
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 2e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int a[N];
int f[N];
int cnt;
int dfs(int u, int fa) {
f[u] = a[u];
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j == fa) continue;
int t = dfs(j, u);
if (t == k) cnt ++;
else f[u] ^= t;
}
return f[u];
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int T;
cin >> T;
while (T -- ) {
memset(h, -1, sizeof h), idx = 0;
cin >> n >> m;
k = 0;
for (int i = 1; i <= n; i ++ ) {
cin >> a[i];
k ^= a[i];
}
for (int i = 0; i < n - 1; i ++ ) {
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
if (!k) {
cout << "YES" << endl;
continue;
}
if (m >= 3) {
cnt = 0;
dfs(1, -1);
if (cnt >= 2) cout << "YES" << endl;
else cout << "NO" << endl;
}
else cout << "NO" << endl;
}
return 0;
}