[ARC120C] Swaps 2 题解

· · 题解

好题。

首先,A 中任意一个元素向前移动 x 就会增加 x,向后相反。你可以将这理解为,如果一个元素在位置 i,那么其就会额外增加一个 n-i+1 的偏移量(建议在纸上模拟)。因为这个偏移量在每个位置不同,这就很烦,我们可以想个办发让其相同,比如让 A 中每个第 i 个元素再加上 i,这样增加的偏移量就是 n-i+1+i=n+1,具体是多少不重要,只要每个位置的偏移量固定即可。

接下来们就变成给定数组 A,问最少交换多少次任意两个相邻数使其变为 B,求逆序对即可。

代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define fir first
#define sec second
#define pii pair<int, int>
const int N = 2e5 + 5;
int a[N], b[N], n, aser[N], ans;
queue<int> tmp;
map<int, int> ma, mb;
map<int, queue<int>> pos;
namespace fenwickTree {
    const int _N = N;
    struct fenwickTree_sum {
        private:
        int tr[_N];
        int lowbit(int x) {
            return x & (-x);
        }

        public:
        void insert(int x, int y) {
            for(int i = x; i <= n; i += lowbit(i)) {
                tr[i] += y;
            }
        }
        int query(int x) {
            int sum = 0;
            for(int i = x; i; i -= lowbit(i)) {
                sum += tr[i];
            }
            return sum;
        }
    };
}
fenwickTree::fenwickTree_sum tr;
signed main() {
    cin >> n;
    for(int i = 1; i <= n; i ++) {
        cin >> a[i];
        a[i] += i, ma[a[i]] ++;
        pos[a[i]].push(i);
    }
    for(int i = 1; i <= n; i ++) {
        cin >> b[i];
        b[i] += i, mb[b[i]] ++;
    }
    for(pii x : ma) {
        if(x.sec != mb[x.fir]) {
            return cout << -1 << endl, 0;
        }
        mb[x.fir] = 0;
    }
    for(int i = 1; i <= n; i ++) {
        aser[i] = pos[b[i]].front(), pos[b[i]].pop();
    }
    for(int i = 1; i <= n; i ++) {
        ans += (i - 1 - tr.query(aser[i])), tr.insert(aser[i], 1);
    }
    return cout << ans << endl, 0;
}