欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ICPC NEAU Programming Contest 2020 M. 再来异或

程序员文章站 2022-05-12 11:43:56
...

ICPC NEAU Programming Contest 2020 M. 再来异或
思路:
每个边的会算 siz[v](nsiz[v])siz[v]*(n-siz[v])次,只需要统计算了奇数次的边。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>

using namespace std;

typedef long long ll;
const int maxn = 4e5 + 7;
const int INF = 0x3f3f3f3f;

int siz[maxn];
int head[maxn],nex[maxn],to[maxn],val[maxn],tot;
int ans,n;

void add(int x,int y,int z) {
    to[++tot] = y;
    val[tot] = z;
    nex[tot] = head[x];
    head[x] = tot;
}

void dfs(int u,int fa) {
    siz[u] = 1;
    for(int i = head[u];i;i = nex[i]) {
        int v = to[i],w = val[i];
        if(v == fa) continue;
        dfs(v,u);
        siz[u] += siz[v];
        ll num = 1ll * siz[v] * (n - siz[v]);
        if(num % 2 == 1) {
            ans ^= w;
        }
    }
}

int main() {
    int T;scanf("%d",&T);
    while(T--) {
        ans = 0;
        memset(head,0,sizeof(head));
        tot = 0;
        scanf("%d",&n);
        for(int i = 1;i < n;i++) {
            int x,y,z;scanf("%d%d%d",&x,&y,&z);
            add(x,y,z);add(y,x,z);
        }
        dfs(1,-1);
        printf("%d\n",ans);
    }
    return 0;
}