关于并查集的经典案例

题目如图:

This is question
样例输入:
4 2
14
2 3
输出:
2

样例输入:
7 5
1 2
2 3
3 1
1 4
5 6
样例输出:
3

代码如下:(很经典,当作为模板使用)

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <vector>
#define MAX 1000
using namespace std;
int father[MAX] = {0};
vector<int> G[MAX];
void init(int n)
{
for(int i = 0 ; i < n ; ++i)
{
father[i] = i;
}
}
int findFather(int x)
{
int a = x;
while(x != father[x])
x = father[x];
while(a != father[a])
{
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
void Union(int a , int b)
{
int faA = findFather(a);
int faB = findFather(b);
if(faA != faB)
{
father[faA] = faB;
}
}
bool isRoot[MAX] = {false};
int calBlock(int n)
{
int Block = 0;
int i;
for(i = 0 ; i < n ; ++i)
{
isRoot[findFather(i)] = true;
}
for(i = 0 ; i < n ; ++i)
{
Block += isRoot[i];
}
return Block;
}
int main()
{
int n , m;
cin>>n>>m;
init(n);
int i ;
for(i = 0 ; i < m ; ++i)
{
int a , b;
cin>>a>>b;
G[a].push_back(b);
G[b].push_back(a);
Union(a , b);
}
int Block = calBlock(n);
cout<<Block<<endl;
return 0;
}

热评文章