题目链接:https://www.luogu.com.cn/problem/P1955
分析:
首先看到题目中有两种关系,会想到带权并查集,但发现并不适用,反而有点复杂,其次看了元素的范围之后才发现这道题应该就是普通并查集,难点在于对元素进行离散化,使得元素大小缩小到下标可以表示的范围。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1e7;
int f[N],b[N],cnt;
struct Node {
int x,y,e;
bool operator < (const Node& b) const {
return e > b.e;
}
} a[N];
int find(int x)// 路径压缩
{
return f[x] == x ? x : f[x] = find(f[x]);
}
int main()
{
int T,n;
scanf("%d",&T);
while(T--) {
scanf("%d",&n);
cnt = 0;
for(int i = 0; i < n; i++) {
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].e);
b[cnt++] = a[i].x;// 保存所有元素到数组中
b[cnt++] = a[i].y;
}
sort(b,b + cnt);
cnt = unique(b,b + cnt) - b;// 去除重复元素,返回末尾地址,注意要先排序
sort(a,a + n);// 按照e从大到小排序
// 离散化
for(int i = 0; i < n; i++) {
a[i].x = lower_bound(b,b + cnt,a[i].x) - b;// 获得相对位置
a[i].y = lower_bound(b,b + cnt,a[i].y) - b;
f[a[i].x] = a[i].x;// 初始化
f[a[i].y] = a[i].y;
}
int flag = 1;
for(int i = 0; i < n; i++) {
int u = find(a[i].x),v = find(a[i].y);
if(a[i].e) f[u] = v;// 当e==1,不管是否在一个集合中都可以合并
else if(u == v) {flag = 0;break;}// 当e==0并且u和v在同一集合中
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}