/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 275ms 10.598 MiB
#3 Accepted 72ms 6.75 MiB
#4 Accepted 52ms 6.609 MiB
#5 Accepted 70ms 10.543 MiB
#6 Accepted 215ms 1.512 MiB
#7 Accepted 33ms 628.0 KiB

Code

#include <bits/stdc++.h>

using i64 = long long;

void solve() {
    int n, q;
    std::cin >> n >> q;
    std::vector<int> a(n);
    for (int i = 0; i < n; i++) {
        std::cin >> a[i];
        a[i]--;
    }
    std::vector<int> pa(n), sz(n);
    std::iota(pa.begin(), pa.end(), 0);
    std::fill(sz.begin(), sz.end(), 1);
    auto find = [&](int x) {
        int cur = x;
        while (x != pa[x]) {
            x = pa[x];
        }
        if (cur != x) {
            pa[cur] = x;
        }
        return x;
    };
    auto merge = [&](int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) {
            return false;
        }
        if (sz[x] < sz[y]) {
            std::swap(x, y);
        }
        pa[y] = x;
        sz[x] += sz[y];
        return true;
    };
    for (int i = 0; i < q; i++) {
        int l, r;
        std::cin >> l >> r;
        l--;
        r--;
        merge(l, r);
    }
    std::unordered_map<int, std::vector<int>> g;
    for (int u = 0; u < n; u++) {
        g[find(u)].push_back(u); 
    }
    int ans = 0;
    for (auto [_, gr] : g) {
        std::unordered_set<int> s;
        for (auto i : gr) {
            s.insert(a[i]);
        }
        for (auto i : gr) {
            if (s.find(i) != s.end()) {
                ans++;
            }
        }
    }
    std::cout << ans << "\n";
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);

    int t;
    std::cin >> t;
    while (t--) {
        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 14:57:22
Judged At
2025-01-02 14:57:22
Judged By
Score
100
Total Time
275ms
Peak Memory
10.598 MiB