Skip to content

Commit

Permalink
2023-12-08
Browse files Browse the repository at this point in the history
  • Loading branch information
ShapeLayer committed Dec 8, 2023
1 parent 6341437 commit 01d33bd
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions tasks/online_judge/baekjoon/cpp/24391.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <bits/stdc++.h>
#define MAX 100'000
using namespace std;

int parents[MAX];

int find(int n) {
if (parents[n] == n) return n;
return parents[n] = find(parents[n]);
}

void merge(int a, int b) {
int pa = find(a), pb = find(b);
if (pa > pb) {
parents[pa] = pb;
parents[a] = pb;
} else {
parents[pb] = pa;
parents[b] = pa;
}
}

int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n + 1; i++) parents[i] = i;
int a, b;
for (int i = 0; i < m; i++) {
cin >> a >> b;
merge(a, b);
}
int count = 0;
int prev, now;
cin >> prev;
for (int i = 1; i < n; i++) {
cin >> now;
if (find(prev) != find(now)) count++;
prev = now;
}
cout << count << endl;
return 0;
}

0 comments on commit 01d33bd

Please sign in to comment.