并查集详解
https://blog.csdn.net/sjystone/article/details/115406797
程序自动分析 https://www.acwing.com/problem/content/239/
离散化 + 并查集
离散化:
1)有序:排序 去重 二分
2)无序:哈希表 / map
将相等的条件放到一个集合中
遍历不相等条件,若在一个集合中则不满足
#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 1000010;
int p[N], n, cnt, T;
unordered_map<int, int> mp;
struct Query{
int a, b, e;
} query[N];
int find(int x)
{
if ( x != p[x] ) p[x] = find(p[x]);
return p[x];
}
int get(int x)
{
if ( !mp.count(x) ) mp[x] = ++ cnt; //离散(无序)
return mp[x];
}
int main()
{
cin >> T;
while ( T -- )
{
cin >> n;
cnt = 0;
bool judge = false;
mp.clear();
for ( int i = 1; i <= n; i ++ )
{
int a, b, e;
cin >> a >> b >> e;
query[i] = {get(a), get(b), e};
}
for ( int i = 1; i <= cnt; i ++ ) p[i] = i; //到cnt,易错
for ( int i = 1; i <= n; i ++ )
if ( query[i].e == 1 )
{
int a = query[i].a, b = query[i].b;
int pa = find(a), pb = find(b);
p[pa] = pb;
}
for ( int i = 1; i <= n; i ++ )
if ( query[i].e == 0 )
{
int a = query[i].a, b = query[i].b;
if ( find(a) == find(b) )
{
judge = true;
break;
}
}
if ( judge ) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}