Xor Path

Xor Path

思路

先是看错题目,以为是所有的路径异或值的和,然后好像用了个假的print函数,一直wa,,,

既然是异或,那么当一个点出现的次数是偶数次的时候它会被自己异或成零,也就是队整体的答案没有贡献度,所以我们只要统计有多少条路经过了这个点就行了。我们得到一个节点的每一个儿子的节点数量,然后再剩下不是当前节点中选择一个节点,两个建立一条边,计算得到当前节点的儿子连儿子构成的最短路对这个点的贡献度,然后再加上这个点与其儿子链接的贡献度即可,如果是奇数则异或上我们的答案,否则这个点将会对答案没有贡献。

代码

/*
  Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define endl '\n'
  
using namespace std;
  
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
  
const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;
  
inline ll read() {
    ll f = 1, x = 0;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-') f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    return f * x;
}
  
void print(ll x, char c) {
    if(x < 10) {
        putchar(x + 48);
        putchar(c);
        return ;
    }
    print(x / 10, c);
    putchar(x % 10 + 48);
}
  
const int N = 5e5 + 10;
  
int head[N], to[N << 1], nex[N << 1], cnt = 1;
int value[N], sz[N], n, ans;
  
void add(int x, int y) {
    to[cnt] = y;
    nex[cnt] = head[x];
    head[x] = cnt++;
}
  
void dfs(int rt, int fa) {
    sz[rt] = 1;
    ll num = 0;
    for(int i = head[rt]; i; i = nex[i]) {
        if(to[i] == fa) continue;
        dfs(to[i], rt);
        sz[rt] += sz[to[i]];
        num += 1ll * sz[to[i]] * (n - sz[to[i]] - 1);
    }
    num += 1ll * (n - sz[rt]) * (sz[rt] - 1);
    num >>= 1;//这个地方每两个节点回重复计算一次因此要除以e2,
    num += n - 1;//加上从这个节点出发的点的贡献度。
    if(num & 1) ans ^= value[rt];
}
  
int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    n = read();
    for(int i = 1; i < n; i++) {
        int x = read(), y = read();
        add(x, y);
        add(y, x);
    }
    for(int i = 1; i <= n; i++) value[i] = read();
    dfs(1, 0);
    printf("%d\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45483201/article/details/107669449