题解:P12333 n 方排序

· · 题解

P12333 n 方排序

解题思路

完善程序

AC CODE

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 5000 + 5;
int a[MAXN];

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

    int n, q;
    cin >> n >> q;
    for (int i = 1; i <= n; ++i) cin >> a[i];

    set<int> bad;                   // 错位下标集合 S
    for (int i = 1; i <= n; ++i)
        if (a[i] != i) bad.insert(i);

    long long last = 0;
    while (q--) {
        int x0, y0; cin >> x0 >> y0;
        int x = (x0 - 1 + last) % n + 1;
        int y = (y0 - 1 + last) % n + 1;

        if (x != y) {
            bad.erase(x);
            bad.erase(y);
            swap(a[x], a[y]);
            if (a[x] != x) bad.insert(x);
            if (a[y] != y) bad.insert(y);
        }

        long long ans = 1;
        if (!bad.empty()) {
            long long len = *bad.rbegin() - *bad.begin() + 1LL;
            ans = len * len;
        }
        cout << ans << '\n';
        last = ans;
    }
    return 0;
}