分块做法。
首先题目其实就是让你求出有多少对 满足 。
如果 和 不在同一个块内,设 表示第 个块内 出现了几次,那么答案就是 ,枚举 后 直接前缀和即可。
如果 和 在同一个块,这样的 对数只有 个,全部找出来即可。实现可以先枚举块,再枚举 ,把 前面的数丢到桶里。
时间复杂度 ,由此可知 左右最优,空间离线后逐块处理可以做到线性。
Code
// They say that life is always easier
// After you let yourself come undone
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e5 + 10;
const int Q = 1e6 + 10;
struct Node {
int x, id, sgn;
};
int n, k, q, a[N], b[N], c[N], pre[N], buk[N];
ll ans[Q];
vector<Node> p[N];
vector<int> pos[N];
void Add(int pos, int k) {
while(pos) c[pos] += k, pos -= pos & -pos;
}
int Sum(int pos) {
int ans = 0;
while(pos <= k) ans += c[pos], pos += pos & -pos;
return ans;
}
int main() {
freopen("data.in", "r", stdin);
freopen("code.out", "w", stdout);
cin.tie(0)->sync_with_stdio(0);
cin >> n >> k >> q;
for(int i = 1; i <= n; ++i) cin >> a[i];
for(int i = 1; i <= k; ++i) b[i] = i;
for(int i = 1; i <= n; ++i)
ans[0] += Sum(a[i] + 1), Add(a[i], 1);
for(int i = 1; i <= q; ++i) {
int x; cin >> x;
p[b[x + 1]].push_back({b[x], i, 1});
p[b[x]].push_back({b[x + 1], i, -1});
swap(b[x], b[x + 1]);
}
int B = 4000;
for(int l = 1, r; l <= n; l = r + 1) {
r = min(l + B - 1, n);
for(int i = l; i <= r; ++i)
pos[a[i]].push_back(i);
for(int x = 1; x <= k; ++x) {
for(int i : pos[x])
for(int j = l; j < i; ++j) buk[a[j]]++;
for(Node i : p[x])
ans[i.id] += 1ll * i.sgn * (pre[i.x] * pos[x].size() + buk[i.x]);
for(int i : pos[x])
for(int j = l; j < i; ++j) buk[a[j]]--;
}
for(int i = l; i <= r; ++i) pre[a[i]]++;
for(int x = 1; x <= k; ++x) pos[x].resize(0);
}
for(int i = 1; i <= q; ++i)
printf("%lld\n", ans[i] += ans[i - 1]);
return 0;
}