第一眼看这道题秒速写并查集然后WA了,仔细看数据吓了一跳,1e9的数太大,而且数字之间不需要确切的比较,只需要清楚他们的大小关系。所以,对他们进行离散化就ok
下面是AC代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int p[maxn], book[maxn], n, res,T; // p和并查集一块用,book表示离散化后的数组
bool flag;
struct node
{
int x, y, e;
}d[maxn];
bool cmp (node a, node b) {
return a.e > b.e; // 把e == 1的放前面
}
void init() { // 初始化
memset(p, 0, sizeof(p));
memset(d, 0, sizeof(d));
memset(book, 0, sizeof(book));
flag = true;
}
int find_(int x) { // 路径压缩
while (x != p[x]) x = p[x] = p[p[x]];
return x;
}
void unite(int x, int y) {
x = find_(x);
y = find_(y);
if (x != y) p[x] = y;
}
int main()
{
cin >> T;
while (T--) {
int tot = 0;
init();
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> d[i].x >> d[i].y >> d[i].e;
book[tot++] = d[i].x, book[tot++] = d[i].y;
}
sort (book, book + tot); // 先排序
res = unique (book, book + tot) - book; // 再去重
for (int i = 1; i <= n; i++) {
d[i].x = lower_bound (book, book + res, d[i].x) - book; // 离散化数字
d[i].y = lower_bound (book, book + res, d[i].y) - book;
}
sort (d + 1, d + n + 1, cmp); // 排序
for (int i = 1; i <= res; i++) p[i] = i;
for (int i = 1; i <= n; i++) {
if (d[i].e) unite(d[i].x, d[i].y);
else if (!d[i].e &&find_(d[i].x) == find_(d[i].y)) {
flag = false;
break;
}
}
if (flag) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}