[ARC120C] Swaps 2 题解
好题。
首先,
接下来们就变成给定数组
代码:
#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;
}