SSL_1224&&P2024&&ybtoj [graph theory] 1 chapter 4 questions [food chain]

Food chain

topic

Food chain


Parsing

Here we need to introduce a new union search set: extended domain union search set.
It uses the idea of ​​splitting points in graph theory: divide a point with multiple information into multiple points with one information respectively.
Three domains: self-food domain, self-food domain, and self-food domain.
Note that the root search is at each level. Find the roots of the roots separately

code:

#include<cstdio>
#include<iostream>
using namespace std;
int s=0,f[150010],q,x,y,z,n;
bool ok;
int find(int dep)
{
    
    
	if(f[dep]==dep)return dep;
	return f[dep]=find(f[dep]);
}
bool check(int x,int y)
{
    
    
	if(find(x)==find(y))return 1;
	return 0;
}
void merge(int x,int y)
{
    
    
	f[find(y)]=find(x);
}
int main()
{
    
    
	scanf("%d%d",&n,&q);
	for(int i=1;i<=3*n;i++)f[i]=i;
	while(q--)
	{
    
    
		scanf("%d%d%d",&z,&x,&y);
		if(x>n||y>n)
		{
    
    
			s++;
			continue;
		}
		if(z==1)
		{
    
    
			if(check(x,y+n)||check(x,y+2*n))s++;
			else merge(x,y),merge(x+n,y+n),merge(x+2*n,y+2*n);
		}
		else
		{
    
    
			if(check(x,y)||check(x,y+2*n))s++;
			else merge(x,y+n),merge(x+n,y+2*n),merge(x+2*n,y);
		}
	}
	printf("%d",s);
	return 0;
}

Guess you like

Origin blog.csdn.net/zhanglili1597895/article/details/112995184