nowcoder—Beauty of Trees

  • Beauty of Trees

  • Now there is an array with a given length, but the elements in the array are unknown. There are m propositions, each giving you l, r, and k. It means that the XOR sum from l to r is k. If you can determine that this is a false proposition based on the known true proposition, output the number of the proposition. If it is a true proposition, no action is required. If you don't know if this is a true proposition or a false proposition, then treat this proposition as a true proposition.


  • The weights can be checked and set.

  • For each proposition, first determine whether the two nodes are in the same tree. If it is on the same tree, it means that the XOR value between these two points exists and is known. Then inquire. The val value of the record (l-1) to the root is x, the val value of the record r to the root is y, and x^y is the XOR value of these two points. Compare with k.

  • If the two points are not on a tree, which means that the XOR value between the two points is unknown, then according to the requirement, this proposition is regarded as a true proposition. So the two trees need to be merged. Record x as the XOR value of l-1 to his root, and record y as the XOR value of r to his root. At this point, we can find that x^y^k is the XOR value between the two roots. Since the initial val of the two roots is empty, you only need to modify the val of one of the points to x^y^k.


#include"stdio.h"
#include"string.h"
int val[105000];
int father[105000];
int getfather(int k){
	if (k==father[k]) return k;
	int tmp=father[k];
	father[k]=getfather(father[k]);
	val[k]=val[k]^val[tmp];
	return father[k];
}
int main(){
	int n,m,i,e,t,xx,yy,a,b,x,y,k,tmp;
	int sign=0;
	scanf("%d %d",&n,&m);
	memset(val,0,sizeof(val));
    for (i=0;i<=n;i++) father[i]=i;
	for (e=1;e<=m;e++){
	  scanf("%d %d %d",&x,&y,&k);
	  x--;
	  if (x>y) {
	  	tmp=x;x=y;y=tmp;
	  }
	  xx=getfather(x);
	  yy=getfather(y);
	  a=val[x];
	  b=val[y];
	  if (xx!=yy){
	  	father[yy]=xx;
	  	val[yy]=k^a^b;
	  }else {
	  	if ((a^b)==k) ;
	  	else {sign=1;printf("%d\n",e);}
	  	
	  }
	}
	if (sign==0) printf("-1\n");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645905&siteId=291194637