题面:https://www.luogu.org/problemnew/show/P1955
本题可以把等于的并在一起,碰到不等于的就判断是否矛盾。由于数据比较大,注意要离散化。
Code:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<ctime>
using namespace std;
const int N=1000005;
int t,n,len,b[N],fa[N];
bool flag;
struct Node
int i,j,e;
a[N];
bool cmp(Node a,Node b)
return a.e>b.e;
int find(int x)
if(fa[x]==x)
return fa[x];
return fa[x]=find(fa[x]);
void merge(int a,int b)
int x=find(a),y=find(b);
if(x!=y)
fa[x]=y;
int main()
scanf("%d",&t);
while(t--)
scanf("%d",&n);
len=0;
for(int i=1;i<=n;i++)
scanf("%d%d%d",&a[i].i,&a[i].j,&a[i].e);
b[++len]=a[i].i;
b[++len]=a[i].j;
sort(a+1,a+1+n,cmp);
sort(b+1,b+1+len);
len=unique(b+1,b+len+1)-(b+1);
for(int i=1;i<=len;i++)
fa[i]=i;
flag=true;
for(int i=1;i<=n;i++)
a[i].i=lower_bound(b+1,b+len+1,a[i].i)-b;
a[i].j=lower_bound(b+1,b+len+1,a[i].j)-b;
if(a[i].e)
merge(a[i].i,a[i].j);
else if(find(a[i].i)==find(a[i].j))
flag=false;
break;
if(flag)
printf("YES\n");
else
printf("NO\n");
return 0;