题解:AT_abc479_f [ABC479F] Narrow Passage

· · 题解

题意简述

有 n 个人在数轴上,初始坐标为 s_1,s_2,\dots,s_n。你可以执行以下操作:

问 n 个人最后分别在 t_1,t_2,\dots,t_n 的最小操作数。n \le 2 \times 10^5。

思路

如果没有人交换位置的情况,答案显然是 \sum_{i=1}^n |s_i - t_i|。

我们称满足 s_i < s_j \land t_i > t_j 的 (i,j) 为“逆序对”。对于任意一对逆序对 (i,j),i 必须穿过 j 才能使坐标大于 j。而无论是 i 向右还是 j 向左,其都是使用了一次操作时 i 向右 1,j 向左 1。

这样所有的交换操作也确定了,不妨先处理所有的交换操作。这样问题就化归为了没有交换的情况,答案即:

\sum_{i=1}^n |s_i + \sum_{j=1}^n [s_i < s_j \land t_i > t_j] - \sum_{j=1}^n [s_i > s_j \land t_i < t_j] - t_i| + \sum_{1 \le i,j \le n} [s_i < s_j \land t_i > t_j]

而绝对值内的求和和逆序对数可以按 s_i 排序并对 t_i 离散化后使用树状数组简单求解。时间复杂度 O(n \log n),可以通过。

代码

#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';
}