From 25c18393110d1f8863037d494aba9601a11d8f62 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Thu, 25 Jul 2024 20:20:59 +0800 Subject: [PATCH] P3420 [POI2005] SKA-Piggy Banks https://www.luogu.com.cn/record/168548666 --- Luogu/P3420/P3420.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Luogu/P3420/P3420.cpp diff --git a/Luogu/P3420/P3420.cpp b/Luogu/P3420/P3420.cpp new file mode 100644 index 00000000..03cf5878 --- /dev/null +++ b/Luogu/P3420/P3420.cpp @@ -0,0 +1,47 @@ +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 1e6 + 5; + +int n, fa[N], cnt; + +int find(int x) { + return x == fa[x] ? x : fa[x] = find(fa[x]); +} + +void merge(int x, int y) { + x = find(x); + y = find(y); + + if (x != y) { + fa[x] = y; + } +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n; + + for (int i = 1; i <= n; i++) { + fa[i] = i; + } + + for (int i = 1, x; i <= n; i++) { + cin >> x; + + merge(i, x); + } + + for (int i = 1; i <= n; i++) { + if (fa[i] == i) cnt++; + } + + cout << cnt << endl; + + return 0; +}