2018华科校赛A题 – Beauty of Trees(带权并查集)
题目描述
It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
One day the tree manager wants to play a game with you. There are N trees lining up in a straight road. The beauty of a set of trees is defined as the bitwise XOR sum of the heights of these trees. The game will last for M rounds, and each time he will tell you an interval [Li,Ri] and its beauty. However, he mixed some fake messages with the correct ones. Your task is to find the messages that cannot logically correspond to its former correct messages. Otherwise you’ll think the message is correct.
输入描述:
The first line contains two integer N and M(1≤N,M≤105), the number of trees and the rounds of game.
Then M lines followed, in each line are three integer L, R and k(1≤L≤R≤N,0≤k≤109), indicating that the beauty of [Li,Ri] is k.
输出描述:
If the i-th message is wrong, then print i in a single line.
If there is no mistake, print -1.
示例1
输入
3 4
1 3 6
1 2 5
3 3 10000
3 3 3
输出
3
说明
You can infer from the first two messages that the height of the third tree is 3.
题意
第一行n和m,n表示有n个点,m表示有m个操作;
接下来m行,每行为l r v 表示区间[l,r]内所有数字的异或和。
对于每个操作,如果和之前做过的操作不矛盾,就进行这个操作,不然不进行操作并输出它的编号,全都不矛盾输出-1。
解题思路
大概维护一个前缀异或和的东西,比如 l r v 就变成 r 的前缀异或和减去 l-1 的前缀异或和等于 v。Rank[x]就表示x的前缀异或和减root[x]的前缀异或和。
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <set>
#define LL long long
using namespace std;
const LL maxn=100007;
int root[maxn],Rank[maxn];
void init(int x)
{
for(int i=0;i<=x;i++)
{
root[i]=i;
Rank[i]=0;
}
}
int find_root(int x)
{
int fx=root[x];
if(x==fx) return x;
else
{
root[x]=find_root(fx);
Rank[x]=Rank[x]^Rank[fx];
}
return root[x];
}
void join(int x,int y,int v)
{
int xx=find_root(x),yy=find_root(y);
root[yy]=xx;
Rank[yy]=Rank[x]^Rank[y]^v;
}
bool check(int x,int y,int v)
{
int xx=find_root(x),yy=find_root(y);
//printf("x=%d,y=%d,xx=%d,yy=%d\n",x,y,xx,yy);
//printf("Rank[%d]=%d rank[%d]=%d\n",x,Rank[x],y,Rank[y]);
if(xx==yy)
{
//printf("v=%d\n",v);
if((Rank[x]^Rank[y])==v) return 1;
else return 0;
}
join(x,y,v);
return 1;
}
int main()
{
int n,k,i,j,x,y,v,flag;
scanf("%d%d",&n,&k);
init(n);
flag=1;
for(i=1;i<=k;i++)
{
scanf("%d%d%d",&x,&y,&v);
if(!check(x-1,y,v))
{
flag=0;
printf("%d\n",i);
}
}
if(flag)
printf("-1\n");
return 0;
}