题意简述
有 个人在数轴上,初始坐标为 。你可以执行以下操作:
- 选定一个人,将其坐标加一或减一。如果终点有人,则把终点处的人换到他的起点处。
问 个人最后分别在 的最小操作数。。
思路
如果没有人交换位置的情况,答案显然是 。
我们称满足 的 为“逆序对”。对于任意一对逆序对 , 必须穿过 才能使坐标大于 。而无论是 向右还是 向左,其都是使用了一次操作时 向右 , 向左 。
这样所有的交换操作也确定了,不妨先处理所有的交换操作。这样问题就化归为了没有交换的情况,答案即:
而绝对值内的求和和逆序对数可以按 排序并对 离散化后使用树状数组简单求解。时间复杂度 ,可以通过。
代码
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
int n, v;
struct Fenwick {
int tree[200007];
void clear() { memset(tree, 0, sizeof(tree)); }
void add(int x, int d) {
while (x <= v) {
tree[x] += d;
x += x & -x;
}
}
int pre_sum(int x) {
int ans = 0;
while (x > 0) {
ans += tree[x];
x -= x & -x;
}
return ans;
}
int range_sum(int l, int r) { return pre_sum(r) - pre_sum(l - 1); }
} t;
struct node {
int s, t;
node(int _s = 0, int _t = 0) : s(_s), t(_t) {}
bool operator<(const node &oth) const { return s < oth.s; }
} a[200007];
int rk[200007];
int val[200007];
void init() {
for (int i = 1; i <= n; i++)
val[i] = a[i].t;
sort(val + 1, val + n + 1);
v = unique(val + 1, val + n + 1) - val - 1;
for (int i = 1; i <= n; i++)
rk[i] = lower_bound(val + 1, val + v + 1, a[i].t) - val;
}
int dt[200007];
i64 ans = 0;
signed main() {
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i].s;
for (int i = 1; i <= n; i++)
cin >> a[i].t;
sort(a + 1, a + n + 1);
init();
for (int i = 1; i <= n; i++) {
dt[i] = t.range_sum(rk[i] + 1, v);
ans += dt[i];
t.add(rk[i], 1);
}
t.clear();
for (int i = n; i >= 1; i--) {
ans += abs(a[i].s - dt[i] + t.pre_sum(rk[i] - 1) - a[i].t);
t.add(rk[i], 1);
}
cout << ans << '\n';
}