原题链接:https://www.acwing.com/problem/content/description/239/
考察点:离散化+并查集。由于题目中直接开并查集数组的话,范围会到1e9,数组直接爆掉。但是输入中只用到了1e6个数,所以把这1e6个数进行离散化。
先处理输入中的所有相等关系,把 相等关系划到一个集合里边,然后对于每个不等关系进行判断即可。
// 并查集数组有点大,所以需要离散化。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<unordered_map>
using namespace std;
const int N = 2000010;
int n, m;
int p[N];
unordered_map<int, int> S;
struct Query
{
int x, y, e;
}query[N];
int get(int x)
{
// 如果之前没存,就新开一个
if(S.count(x) == 0) S[x] = ++n;
// 返回离散化之后的值。
return S[x];
}
int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
int T;
cin >> T;
while(T--)
{
// 离散化从0开始
n=0;
S.clear();
scanf("%d", &m); // m个条件
for(int i=0; i<m; i++)
{
int x, y, e;
scanf("%d%d%d", &x, &y, &e);
// 直接用x,y离散化之后的值
query[i] = {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;
}
// 检查所有不相等条件
bool has_conflit = false;
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)
{
has_conflit =true;
break;
}
}
if(has_conflit) puts("NO");
else puts("YES");
}
return 0;
}