跳到正文

题解

[ARC120C] Swaps 2 题解

Pretharp约 3 分钟
原文
文章信息与版本

文章信息

发布
2023年6月2日
收录
2026年10月13日
更新
2026年11月16日
篇幅
约 3 分钟
获赞
4

版本

  1. v1当前

好题。

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

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

代码:

C++
#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;
}
原文
存档评论1 条抓取于