猫猫们,是加强版,我们有救了喵!
因为时限给的非常充裕,加上我最近刚换了一个光滑的新脑子,所以我要分块块喵。
考虑计算每一次更改 ,()对于原来逆序对个数的代价喵。猫猫们如果发现 了记得换一下喵。
对于两边的散块块:
依次遍历每个数 。如果 ,那么当把 换到后面去了以后,逆序对的个数就减少了喵;要是 ,那么把 换到后面去,逆序对的个数就多了一个喵。
同理, 也可以这样去想喵。
对于中间的大块块:
对于每一个大块块我们都开一个树状数组喵,用来记录大块块中每一个数的个数。对于 ,我们遍历每一个中间的大块块,然后整体的考虑 移到后面会造成什么影响:交换完后,块块中原本大于 的数的个数被加上了,块块中小于 的数的个数被减掉了。
同理, 也可以这样处理喵。
如果有些晕晕可以看看猫猫用爪爪敲的一点点代码喵:
注意块长喵,因为有个树状数组,如果你直接取 可能会 T 掉喵(?)
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 2e5 + 10, maxm = 1880;
#define ll long long
int n, m;
int a[maxn], b[maxn];
int blo[maxn], blocnt, siz, l[maxn], r[maxn];
ll res[maxn], ans;
struct BIT
{
ll c[maxn];
ll lowbit(ll x) { return x & (-x); }
void add(int x, ll y)
{
if (x <= 0) return;
for (; x <= n; x += lowbit(x))
c[x] += y;
}
ll query(int x)
{
if (x <= 0) return 0;
ll res = 0;
for (; x; x -= lowbit(x))
res += c[x];
return res;
}
} t[maxm];
int main()
{
std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0);
cin >> n;
siz = sqrt(n * log2(n));
for (int i = 1; i <= n; i++) cin >> a[i], b[i] = a[i], blo[i] = i / siz + (i % siz != 0);
sort(b + 1, b + n + 1);
int tot = unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; i++) a[i] = lower_bound(b + 1, b + tot + 1, a[i]) - b;
blocnt = blo[n];
for (int i = 1; i <= n; i++)
{
if (blo[i] != blo[i - 1])
l[blo[i]] = i;
r[blo[i]] = i;
}
for (int i = 1; i <= n; i++)
t[0].add(a[i], 1),
ans += i - t[0].query(a[i]);
cout << ans << "\n";
for (int i = 1; i <= blocnt; i++)
for (int j = l[i]; j <= r[i]; j++)
{
t[i].add(a[j], 1);
res[i] += j - l[i] + 1 - t[i].query(a[j]);
}
cin >> m;
while (m--)
{
int x, y;
cin >> x >> y;
if (x > y) swap(x, y);
int pre = upper_bound(l + 1, l + blocnt + 1, x) - l;
int suf = lower_bound(r + 1, r + blocnt + 1, y) - r - 1;
if (a[x] < a[y]) ans++;
if (a[y] < a[x]) ans--;
if (pre <= suf)
{
for (int i = x + 1; i < l[pre]; i++)
{
if (a[x] < a[i]) ans++;
if (a[x] > a[i]) ans--;
if (a[y] > a[i]) ans++;
if (a[y] < a[i]) ans--;
}
for (int i = pre; i <= suf; i++)
{
ans -= t[i].query(a[x] - 1);
ans += t[i].query(n) - t[i].query(a[x]);
ans -= t[i].query(n) - t[i].query(a[y]);
ans += t[i].query(a[y] - 1);
}
for (int i = r[suf] + 1; i < y; i++)
{
if (a[x] < a[i]) ans++;
if (a[x] > a[i]) ans--;
if (a[y] > a[i]) ans++;
if (a[y] < a[i]) ans--;
}
}
else
{
for (int i = x + 1; i < y; i++)
{
if (a[x] < a[i]) ans++;
if (a[x] > a[i]) ans--;
if (a[y] > a[i]) ans++;
if (a[y] < a[i]) ans--;
}
}
t[pre - 1].add(a[x], -1);
t[suf + 1].add(a[y], -1);
t[pre - 1].add(a[y], 1);
t[suf + 1].add(a[x], 1);
swap(a[x], a[y]);
cout << ans << "\n";
}
return 0;
}猫猫是豪猫,不哈人喵 /w\