题意:
给你一个排列,求分别将其子区间的数reverse之后,得到的数列的逆序对的数目。
分析:
先求出原序列的逆序对的数量,然后固定区间左端点i,移动右端点j,每次通过树状数组求[i, j]中小于a[j]的数目和大于a[j]的数目,计算本次反转对逆序对的贡献,用res记录前面几次贡献的和。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
const ll mod = 1e9 + 7;
const int maxn = 1010;
const int inf = 0x3f3f3f3f;
int a[maxn];
int c[maxn];
int lowbit(int x)
{
return x & (-x);
}
ll sum(int val)
{
ll res = 0;
for(int i = val; i >= 1; i -= lowbit(i))
res += c[i];
return res;
}
void insert(int val)
{
for(int i = val; i < maxn; i += lowbit(i))
c[i]++;
}
int main()
{
int n; cin >> n;
ll ans = 0;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
ans += (i - 1 - sum(a[i]));
insert(a[i]);
}
for(int i = 1; i <= n; i++)
{
ll res = 0;
mem(c, 0);
for(int j = i; j <= n; j++)
{
int small = sum(a[j]);
int large = j - i - small;
// print(small), print(large);
res += small - large;
printf("%d%c", res + ans, i == n && j == n ? '\n' : ' ');
insert(a[j]);
}
}
}