3 1 2 2 1 3 0 2 2 1
1 2
#include"iostream"
#include"cstdio"
#include"cstring"
using namespace std;
int a[100005];
int b[100005]; //辅助数组
long long cnt;
void Merge(int a[],int p,int q,int r, int b[]){
int s = p, t = q + 1, k = p;
while(s <= q && t <= r){
if(a[s] <= a[t]){
b[k ++] = a[s ++];
}else{
b[k ++] = a[t ++];
cnt += (q - s + 1); // 在原序列a[s...q] > a[t],故有逆序数对 (q-s+1) 个
}
}
if(s == q + 1)
for(;t <= r;t ++) b[k ++] = a[t];
else
for(;s <= q;s ++) b[k ++] = a[s];
for(int i = p;i < k;i ++)
a[i] = b[i];
}
void BottomUpSort(int a[],int first,int last,int b[]){
if(first < last){
int mid = (first + last) / 2;
BottomUpSort(a, first, mid, b);
BottomUpSort(a, mid + 1, last, b);
Merge(a, first, mid, last, b);
}
}
int main(){
int n, k;
while(scanf("%d%d",&n,&k) != EOF){
cnt = 0;
for(int i = 1;i <= n;i ++)
scanf("%d",&a[i]);
BottomUpSort(a,1,n, b);
cnt = (cnt - k) > 0 ? (cnt - k) : 0;
//for(int i = 1;i <= n;i ++) printf("%d ",a[i]);
printf("\n");
printf("%I64d\n",cnt);
}
return 0;
}原文:http://blog.csdn.net/keeping111/article/details/51335703