代码
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
inline int read(){
int x=0,f=1;char c=getchar();
while ('0'>c||c>'9') {if (c=='-') f=-1;c=getchar();}
while ('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int maxn(1e6+5);
int n,flag;
int f[maxn];
int cnt;
struct node{
int x,y,z;
bool operator < (const node& x) const{
return z>x.z;
}
}e[maxn];
int b[maxn*3];
inline int find(int x){
return f[x]==x?x:f[x]=find(f[x]);
}
void init(){
n=read();
memset(e,0,sizeof(e));
memset(b,0,sizeof(b));
memset(f,0,sizeof(f));
flag=1;
cnt=0;
for (int i(1);i<=n;++i){
e[i].x=read(),e[i].y=read(),e[i].z=read();
b[++cnt]=e[i].x;
b[++cnt]=e[i].y;
}
sort(b+1,b+cnt+1);
cnt=unique(b+1,b+cnt+1)-b-1;
for (int i(1);i<=n;++i){
e[i].x=lower_bound(b,b+cnt,e[i].x)-b;
e[i].y=lower_bound(b,b+cnt,e[i].y)-b;
}
for (int i(1);i<=cnt;++i) f[i]=i;
sort(e+1,e+1+n);
}
void doit(){
for (int i(1);i<=n;++i){
int x=find(e[i].x),y=find(e[i].y);
if (e[i].z) f[x]=y;
else if (x==y){
puts("NO");
flag=0;
break;
}
}
if (flag) puts("YES");
}
int main(){
int t=read();
while (t--){
init();
doit();
}
return 0;
}