Accepted
Code
#include <bits/stdc++.h>
using namespace std;
// #include "debug.h"
struct dsu {
vector<int> parent, size;
dsu(int n) {
parent.assign(n, -1);
size.assign(n, 0);
}
void makeset(int v) {
parent[v] = v;
size[v] = 1;
}
bool combine(int a, int b) {
a = find(a), b = find(b);
if (a == b)
return false;
if (size[a] < size[b])
swap(a, b);
parent[b] = a, size[a] += size[b];
return true;
};
int find(int v) {
if (v == parent[v])
return v;
return parent[v] = find(parent[v]);
}
};
void solve() {
int n, q;
cin >> n >> q;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
dsu ds(n);
for (int i = 0; i < n; ++i) {
ds.makeset(i);
}
while (q--) {
int u, v;
cin >> u >> v;
--u, --v;
ds.combine(u, v);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += (ds.find(a[i] - 1) == ds.find(i));
}
cout << ans << '\n';
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int tc = 1;
cin >> tc;
while (tc--) {
solve();
}
}
Information
- Submit By
- Type
- Submission
- Problem
- P1119 Maximizing Fixed Points
- Contest
- Happy New Year 2025
- Language
- C++17 (G++ 13.2.0)
- Submit At
- 2025-01-02 15:04:44
- Judged At
- 2025-01-02 15:04:44
- Judged By
- Score
- 100
- Total Time
- 135ms
- Peak Memory
- 1.875 MiB