ACM-ICPC 2017 Asia Urumqi I. A Possible Tree 帶權並查集
Alice knows that Bob has a secret tree (in terms of graph theory) with n nodes with n -1n−1 weighted edges with integer values in [0, 260 - 1][0,260−1]. She knows its structure but does not know the specific information about edge weights.
Thanks to the awakening of Bob’s conscience, Alice gets m conclusions related to his tree. Each conclusion provides three integers u,v and val saying that the exclusive OR (XOR)OR(XOR) sum of edge weights in the unique shortest path between uu and vv is equal to val.
Some conclusions provided might be wrong and Alice wants to find the maximum number WW such that the first WW given conclusions are compatible. That is say that at least one allocation of edge weights satisfies the first WWconclusions all together but no way satisfies all the first W + 1W+1 conclusions (or there are only WW conclusions provided in total).
Help Alice find the exact value of WW .
Input
The input has several test cases and the first line contains an integer t (1 \le t \le 30)t(1≤t≤30) which is the number of test cases.
For each case, the first line contains two integers n (1 \le n \le 100000)n(1≤n≤100000) and c (1 \le c \le 100000)c(1≤c≤100000) which are the number of nodes in the tree and the number of conclusions provided. Each of the following n - 1n−1 lines contains two integers uu and v (1 \le u,v \le n)v(1≤u,v≤n) indicating an edge in the tree between the uu-th node and the vv-th node. Each of the following cc lines provides aa conclusion with three integers uu, vv and val where 1 \le u1≤u, v \le nv≤n and val \in [0, 260 - 1]val∈[0,260−1].
Output
For each test case, output the integer WW in a single line.
樣例輸入複製
2 7 5 1 2 2 3 3 4 4 5 5 6 6 7 1 3 1 3 5 0 5 7 1 1 7 1 2 3 2 7 5 1 2 1 3 1 4 3 5 3 6 3 7 2 6 6 4 7 7 6 7 3 5 4 5 2 5 6
樣例輸出複製
3 4
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxm = 200005;
int p[maxm], sum[maxm];
int find(int k)
{
if (k != p[k])
{
int tmp = p[k];
p[k] = find(p[k]);
sum[k] ^= sum[tmp];
}
return p[k];
}
int main()
{
int n, i, j, k, x, y, tx, ty, val, m, ans, t;
scanf("%d", &t);
while (t--)
{
ans = 0;
scanf("%d%d", &n, &m);
for (i = 0;i <= n;i++)
p[i] = i, sum[i] = 0;
for (i = 1;i < n;i++)
scanf("%d%d", &x, &y);
for (i = 1;i <= m;i++)
{
scanf("%d%d%d", &x, &y, &val);
tx = find(x), ty = find(y);
if (tx == ty)
{
if ((sum[x] ^ sum[y]) != val&&ans == 0)
ans = i;
}
else
{
p[tx] = ty;
sum[tx] = sum[x] ^ val ^ sum[y];
}
}
printf("%d\n", ans - 1);
}
return 0;
}