Problem Description
You have a sequence {a1,a2,...,an} and you can delete a contiguous subsequence of length m. So what is the minimum number of inversions after the deletion.
Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers n,m(1≤n≤105,1≤m<n) - the length of the seuqence. The second line contains n integers a1,a2,...,an(1≤ai≤n).
The sum of n in the test cases will not exceed 2×106.
Output
For each test case, output the minimum number of inversions.
Sample Input
2
3 1
1 2 3
4 2
4 1 3 2
Sample Output
0
1
思路;
假设删除的区间为 b, b左边的区间为a, b右边的区间为c。
初始时a长度为0,b的区间为1-m。
建立两个树状数组分别表示a和c的逆序对。
计算完一次后b区间向右移一位,分别计算左边增加的那个数和右边减少的那个数对a,c的逆序对影响即可。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 100000+10;
typedef long long ll;
int n, m, a[N];
ll b[N*4], c[N*4];
int lowbit(int x)
{
return x & (-x);
}
ll sum(ll *d, int x)
{
int res = 0;
while (x)
{
res += d[x];
x -= lowbit(x);
}
return res;
}
void update(ll *d, ll x, ll v)
{
while (x <= n)
{
d[x] += v;
x += lowbit(x);
}
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int cnt = 0, ans = inf;
scanf("%d%d", &n, &m);
memset(b, 0, (n+3)*sizeof(ll));
memset(c, 0, (n+3)*sizeof(ll));
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
for (int i = m + 1; i <= n; i++)
{
cnt += i - m - 1 - sum(b,a[i]);
update(b,a[i],1);
}
ans = cnt;
for (int i = m + 1; i <= n; i++)
{
cnt += sum(b,a[i-m]-1);
cnt += sum(c,n) - sum(c, a[i-m]);
update(c, a[i-m], 1);
cnt -= sum(b, a[i]-1);
cnt -= sum(c, n) - sum(c,a[i]);
update(b, a[i], -1);
ans = min(ans, cnt);
}
printf("%lld\n", ans);
}
return 0;
}