[AcWing 4290] 小希的迷宫
作者:互联网
并查集 + 树的判定
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int n;
int p[N];
int find(int x)
{
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
void merge(int a, int b)
{
int pa = find(a), pb = find(b);
p[pa] = pb;
}
void solve()
{
for (int Case = 1; ; Case ++) {
int a, b;
bool ok = true;
for (int i = 0; i < N; i ++)
p[i] = i;
while (cin >> a >> b, a > 0) {
// 形成环
if (find(a) == find(b))
ok = false;
else
merge(a, b);
}
if (a == -1)
break;
cout << (ok ? "Yes" : "No") << endl;
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
return 0;
}
- 树的定义存在一些争议,对于算法题中的无向图,可以认为,只要无环即是树
标签:Case,小希,int,4290,long,pb,pa,find,AcWing 来源: https://www.cnblogs.com/wKingYu/p/16592287.html