题解:离散化+并查集
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=2000009; int T; int n; int a[maxn][3]; int b[maxn],nn; int father[maxn]; int Getf(int x){ if(father[x]==x)return x; return father[x]=Getf(father[x]); } void Unionn(int x,int y){ int fx=Getf(x); int fy=Getf(y); if(father[fx]!=fy)father[fx]=fy; } int main(){ scanf("%d",&T); while(T--){ int fla=1; nn=0; scanf("%d",&n); for(int i=1;i<=n;++i){ scanf("%d%d%d",&a[i][1],&a[i][2],&a[i][0]); b[++nn]=a[i][1];b[++nn]=a[i][2]; } sort(b+1,b+1+nn); nn=unique(b+1,b+1+nn)-b-1; for(int i=1;i<=n;++i){ a[i][1]=lower_bound(b+1,b+1+nn,a[i][1])-b; a[i][2]=lower_bound(b+1,b+1+nn,a[i][2])-b; } for(int i=1;i<=nn;++i)father[i]=i; for(int i=1;i<=n;++i){ if(a[i][0]==1)Unionn(a[i][1],a[i][2]); } for(int i=1;i<=n;++i){ if(a[i][0]==0){ if(Getf(a[i][1])==Getf(a[i][2]))fla=0; } } if(fla)printf("YES\n"); else printf("NO\n"); } return 0; }