File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #define MAX 100001
3
+ using namespace std ;
4
+
5
+ int parent[MAX];
6
+ int N, M;
7
+
8
+ int find (int v) {
9
+ if (parent[v] == v) return v;
10
+ return parent[v] = find (parent[v]);
11
+ }
12
+
13
+ void unionNode (int u, int v) {
14
+ u = find (u);
15
+ v = find (v);
16
+ if (parent[u] != parent[v]) parent[v] = u;
17
+ }
18
+
19
+ void func () {
20
+ int pre = -1 ;
21
+ int ret = 0 ;
22
+ int x;
23
+ while (N--) {
24
+ cin >> x;
25
+ int p = find (x);
26
+ if (pre != p) {
27
+ if (pre != -1 ) ret++;
28
+ pre = p;
29
+ }
30
+ }
31
+
32
+ cout << ret << ' \n ' ;
33
+ }
34
+
35
+ void init () {
36
+ for (int i = 1 ; i <= N; i++) {
37
+ parent[i] = i;
38
+ }
39
+ }
40
+
41
+ void input () {
42
+ int u, v;
43
+ cin >> N >> M;
44
+ init ();
45
+ while (M--) {
46
+ cin >> u >> v;
47
+ unionNode (u, v);
48
+ }
49
+ }
50
+
51
+ int main () {
52
+ cin.tie (NULL ); cout.tie (NULL );
53
+ ios::sync_with_stdio (false );
54
+
55
+ input ();
56
+ func ();
57
+
58
+ return 0 ;
59
+ }
You can’t perform that action at this time.
0 commit comments