[NOI2001] Food Chain

  Take the right and check the collection.

  Learning reference: https://agatelee.cn/2017/05/%E5%B8%A6%E6%9D%83%E5%B9%B6%E6%9F%A5%E9%9B%86/

  Precautions and possible doubts.

  1: The weight of the node directly represents the relationship with the root node.

  2: The node weight that may appear in the path compression does not represent the relationship with the current root node, because the node is newly merged.

       And in the path from a node to the root node, at most one point will have such a relationship.

       And this point is a point where no path has been compressed before.

       The weight of this point represents the relationship with the previous node, and the root node before this node must be f[x], that is, the parent node of this node.

       Then w[x] should be ( w[x] + w[f[x]] ) % 3.

// qc

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int M=50000+10;
/****************************************************************/
int f[M],w[M];
int finds(int x) {
	if(f[x]!=x) {
		int tmp=f[x];
		f[x]=finds(f[x]);
		w[x]=(w[tmp]+w[x])%3; // The w[] value of all unpath compressed points is the relation to the previous root node.
	}
	return f[x];
}
/****************************************************************/
int main() {
	freopen("eat.in","r",stdin);
	freopen("eat.out","w",stdout);
	int n,q,opt,x,y,fx,fy,ans=0;
	scanf("%d%d",&n,&q);
	for(int i=1;i<=n;i++) {
		f[i]=i,w[i]=0;
	}
	for(int i=1;i<=q;i++) {
		scanf("%d%d%d",&opt,&x,&y);
		if(x>n||y>n) {
			years++; keep on going;
		}
		if(opt==1) {
			fx=finds(x);
			fy=finds(y);
			if(fx==fy) {
				if(w[x]!=w[y]) ans++;
				continue;
			}
			f[fx]=fy;
			w[fx]=(w[y]-w[x]+3)%3; // w[x]+w[fx]=w[y].
		} else {
			fx=finds(x);
			fy=finds(y);
			if(fx==fy) {
				if(w[x]!=(w[y]+1)%3) ans++;
				continue;
			}
			f[fx]=fy;
			w[fx]=(w[y]-w[x]+4)%3; // w[x]+w[fx]=w[y]+1.
		}
	}
	printf("%d\n",ans);
	return 0;
}

 

Guess you like

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