Time Limit: 3000MS | Memory Limit: 65536KB | 64bit IO Format: %I64d & %I64u |
Description
You have a sequence \{a_1,a_2,...,a_n\} 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 \le n \le 10^5, 1 \le m < n) - the length of the seuqence. The second line contains n integersa_1,a_2,...,a_n (1 \le a_i \le n).
The sum of n in the test cases will not exceed 2 \times 10^6.
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
3 1
1 2 3
4 2
4 1 3 2
Sample Output
0
1
1
Source
BestCoder Round #58 (div.2)
滑动区间扫描。用树状数组来维护逆序对的个数(数组存储数n是否已经出现,通过计算数组前缀和来求逆序对,思路和比这篇早些写的POJ2182 Lost Cows类似)
维护L([i])树状数组表示i左边比a[i]的数的数量,R([i])树状数组表示i右边比a[i]小的数的数量。窗口从左滑到右面,不断更新L和R,计算答案并更新
/*by SilverN*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
const int mxn=;
int n,m;
struct tree{
int a[mxn];
inline lowbit(int x){return x&-x;}
void init(){memset(a,,sizeof a);}
void add(int x,int num){
while(x<=n){
a[x]+=num;
x+=lowbit(x);
}
return;
}
int sum(int x){
int res=;
while(x){
res+=a[x];
x-=lowbit(x);
}
return res;
}
};
int a[mxn];
tree Le,Ri;
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
int i,j;
for(i=;i<=n;i++){
scanf("%d",&a[i]);
}
Le.init();
Ri.init();
long long ans;
long long tmp=;
//求原有逆序对数(最左边滑动窗口内的不算)
for(i=n;i>m;i--){
Ri.add(a[i],);
tmp+=Ri.sum(a[i]-);
}
ans=tmp;
//finish
for(i=;i<=n-m;i++){
Ri.add(a[i+m],-);//窗口滑动,窗口最右面的数被删除
tmp=tmp+Ri.sum(a[i]-)-Ri.sum(a[i+m]-);
tmp=tmp+Le.sum(n+-(a[i]+))-Le.sum(n+-(a[i+m]+));
Le.add(n+-a[i],);
ans=min(ans,tmp);
}
printf("%lld\n",ans);
}
return ;
}