Files
python/TangDou/AcWing_TiGao/T4/237.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

73 lines
1.9 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 200010; // 因为是需要存入左右两个条件xi=xj,这样最多是保存的两倍的n
int m; // m个条件
int b[N], bl; // 离散化数组,数组长度
int p[N]; // 并查集数组
struct Node {
int x, y, e;
} a[N]; // 输入的条件
// 并查集
int find(int x) {
if (x == p[x]) return x;
return p[x] = find(p[x]);
}
// 利用二分计算出x值在已排序数组b中的位置,位置就是新的号码
int get(int x) {
int l = 1, r = bl;
while (l < r) {
int mid = (l + r) >> 1;
if (b[mid] < x)
l = mid + 1;
else
r = mid;
}
return l;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int flag = 0, idx = 0;
scanf("%d", &m);
for (int i = 1; i <= 2 * m; i++) p[i] = i;
for (int i = 1; i <= m; i++) {
scanf("%d %d %d", &a[i].x, &a[i].y, &a[i].e);
b[idx++] = a[i].x, b[idx++] = a[i].y; // 存入离散化数组中,准备处理
}
// 静态数组离散化
sort(b, b + 2 * m);
bl = unique(b, b + 2 * m) - b;
// 相等关系 <=> 同一个并查集
for (int i = 1; i <= m; i++)
if (a[i].e == 1) {
int pa = find(get(a[i].x)), pb = find(get(a[i].y));
if (pa != pb) p[pa] = pb;
}
// 不等关系 与 同一个并查集 存在冲突
for (int i = 1; i <= m; i++)
if (a[i].e == 0) {
int pa = find(get(a[i].x)), pb = find(get(a[i].y));
if (pa == pb) {
flag = 1;
break;
}
}
if (flag)
puts("NO");
else
puts("YES");
}
return 0;
}