刚学并查集做的第一题,数的范围比较大,离散一下
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef pair<int, int> P;
const int N = 2e5 + 5;
vector<P> v1, v2;
unordered_map<int, int> mp;
int fa[N], n, t, tot;
int get_map(int x)
{
if (mp.count(x)) return mp[x];
return mp[x] = tot++;
}
int get(int x)
{
if (fa[x] == x) return x;
return fa[x] = get(fa[x]);
}
void merge(int x, int y)
{
fa[get(x)] = get(y);
}
void init()
{
for (int i = 0; i<tot; i++)
fa[i] = i;
}
int main()
{
cin>>t;
while (t--)
{
cin>>n;
tot = 0;
mp.clear();
v1.clear(), v2.clear();
for (int i = 1; i <= n; i++)
{
int x, y, e;
cin>>x>>y>>e;
x = get_map(x), y = get_map(y);
if (e) v1.push_back(P(x, y));
else v2.push_back(P(x, y));
}
init();
for (auto x : v1)
{
merge(x.first, x.second);
}
bool flag = true;
for (auto x : v2)
{
if (get(x.first) == get(x.second))
{
flag = false;
break;
}
}
puts(flag ? "YES" : "NO");
}
return 0;
}