先把相等条件的放在一个集合中,在考虑不等条件,出现不等条件的祖宗节点是同一个就会有矛盾
import java.util.*;
import java.io.*;
public class Main {
static final int N = 2000010;//取数据的2倍
static int[] p = new int[N];
static Query[] query = new Query[N];
static HashMap<Integer, Integer> hash = new HashMap<>();
static int n, m;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int T = Integer.parseInt(br.readLine());
while (T -- > 0) {
n = 0;//idx标记
hash.clear();//清空hash进行下一轮测试
m = Integer.parseInt(br.readLine());
for (int i = 0; i < m; i++) {
String[] str = br.readLine().split(" ");
int x = Integer.parseInt(str[0]),
y = Integer.parseInt(str[1]),
e = Integer.parseInt(str[2]);
//先离散化在加入query
query[i] = new Query(get(x), get(y), e);
}
//初始化并查集
for (int i = 1; i <= n; i++) p[i] = i;
//合并所有相等约束条件
for (int i = 0; i < m; i++)
if (query[i].e == 1) {
int pa = find(query[i].x), pb = find(query[i].y);
p[pa] = pb;
}
//检查所有的不等条件
boolean flag = true;
for (int i = 0; i < m; i++)
if (query[i].e == 0) {
int pa = find(query[i].x), pb = find(query[i].y);
if (pa == pb) {
flag = false;
break;
}
}
if (flag) out.println("YES");
else out.println("NO");
}
out.flush();
}
static int find(int u) {
if (u != p[u]) p[u] = find(p[u]);
return p[u];
}
/*
不难发现该离散化的value就是插入顺序
本题并不要求离散化的数据有序性,对于有序性的
离散化可以使用排序去重加二分操作,
或者对于hash表的value进行操作
*/
static int get(int x) {
if (!hash.containsKey(x)) hash.put(x, ++n);
return hash.get(x);
}
}
class Query {
int x, y, e;
public Query(int x, int y, int e) {
this.x = x;
this.y = y;
this.e = e;
}
}