[Ybtoj Chapter 10 Example 2] Automatic program analysis [Combined search collection]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


The idea of ​​solving the problem
first satisfy all xi = xj x_i = x_jxi=xjConstraints, just use one and check to maintain

And for xi ≠ xj x_i≠x_jxi=xjCondition, judge xi x_ixiAnd xj x_jxjWhether they are in the same set, if they are, indicate xi x_ixiShould be equal to xj x_jxj , It's contradictory

Then notice that the maximum value of x reaches 1 0 9 10^9109 , so use discretization


Code

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

int t,n,fa[1000010],v[3000010],tot=0;
bool flag=1;
struct c{
    
    
	int x,y,e;
}a[1000010];
int find(int x)
{
    
    
	if(fa[x]!=x)return fa[x]=find(fa[x]);
	else return fa[x];
}
bool cmp(c l,c r){
    
    
	return l.e>r.e;
}
int main(){
    
    
	scanf("%d",&t);
	while(t--)
	{
    
    
		scanf("%d",&n);
		flag=1,tot=0;
		memset(v,0,sizeof(v));
		memset(a,0,sizeof(a));
		memset(fa,0,sizeof(fa));
		for(int i=1;i<=n;i++)
		{
    
    	
			scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].e);
			v[++tot]=a[i].x,v[++tot]=a[i].y;	
		}
		sort(v+1,v+tot+1);
		int len=unique(v+1,v+tot+1)-v;//去重后元素个数
		for(int i=1;i<=n;i++)
		{
    
    
			a[i].x=lower_bound(v+1,v+len+1,a[i].x)-v;
			a[i].y=lower_bound(v+1,v+len+1,a[i].y)-v;
		}
		for(int i=1;i<=len;i++)//并查集
			fa[i]=i;
		sort(a+1,a+n+1,cmp);
		for(int i=1;i<=n;i++)
		{
    
    
			int xx=find(a[i].x),yy=find(a[i].y);
			if(a[i].e==1)
				fa[xx]=yy;
			if(a[i].e==0&&xx==yy)
			{
    
    
				flag=0;
				printf("NO\n");
				break;
			}
		}
		if(flag)printf("YES\n");
	}
} 

Guess you like

Origin blog.csdn.net/kejin2019/article/details/115030068