HDU_1272_(并查集)
- 无向图用并查集判断是否成环.
- 坑点:仅仅考虑了根节点相同(有回路)的情况,而忽略了有多个连通分量,也是不满足 任意两个房间有且仅有一条路径相同
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51#include <iostream>
#include <string.h>
using namespace std;
const int maxn = 1e5+10;
int pre[maxn];
int vis[maxn];
bool flag;
int maxnum;
void init() {
for (int i=0; i<maxn; i++) pre[i] = i;
memset(vis,0,sizeof vis);
flag = true;
maxnum = 0;
}
int find(int x) {
if (x == pre[x]) return x;
return pre[x] = find(pre[x]);
}
void merge(int a,int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) flag = false;
else pre[ra] = rb;
}
int u,v;
int main() {
// freopen("a.txt","r",stdin);
init();
while ( scanf("%d%d",&u,&v) ) {
if ( u == -1 && v == -1 ) return 0;
if ( u == 0 && v == 0 ) {
int cnt = 0;
for (int i=1; i<=maxnum; i++)
if (vis[i] && pre[i] == i) cnt++;
if (flag && cnt<=1) printf("Yes\n");
else printf("No\n");
init();
continue;
}
maxnum = max(maxnum , max(u,v));
vis[u] = 1;
vis[v] = 1;
if (u != v) merge(u,v);
}
return 0;
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!