并查集的裸题,时间很充裕,只要路径压缩怎么写都能过。
自己第一次写的cin版本跑了7000ms。
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
unordered_map<int,int> father;
int n,t;
vector<PII> v;
int find(int a)
{
if (father[a] != a) father[a] = find(father[a]);
return father[a];
}
void Union(int a,int b)
{
int fa = find(a);
int fb = find(b);
if (fa == fb) return ;
father[fb] = fa;
}
int main()
{
scanf("%d",&t);
while (t--)
{
father.clear();
v.clear();
scanf("%d",&n);
for (int i = 1;i <= n;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if (father[a] == 0) father[a] = a;
if (father[b] == 0) father[b] = b;
if (c == 1) Union(a,b);
else v.push_back({a,b});
}
bool flag = true;
for (int i = 0;i < v.size();i++)
{
int fa = find(v[i].first);
int fb = find(v[i].second);
if (fa == fb)
{
flag = false;
break;
}
}
if (flag) printf("YES\n");
else printf("NO\n");
}
}