B题

danielhaohuang 2026-10-03 16:27:52 2026-10-04 12:31:30

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n, p[1000001], ans;
int dis(int x, int y){return (((y - x) >= 0) ? (y - x) : (y - x + n));}
int f(int x)
{
    int l = x, c = x;
    while(p[l] != -1){l = p[l];}
    while(c != l){int q = p[c];p[c] = l;c = q;}
    return l;
}
signed main(){
    freopen("park.in", "r", stdin); freopen("park.out", "w", stdout);
    ios::sync_with_stdio(0);  cin.tie(0);cout.tie(0); cin >> n;
    memset(p, -1, sizeof(p));
    for(int i = 1; i <= n; i ++)
    {
        int x, temp;
        cin >> x; temp = f(x); ans += dis(x, temp);
        if(i != n)p[temp] = (temp + 1) % n;
    } cout << ans << "\n";
    return 0;
}