Frosh Week
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2772 Accepted Submission(s): 923
#include"iostream"
#include"cstdio"
#include"cstring"
using namespace std;
int a[1000005];
int b[1000005]; //輔助數組
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;
while(scanf("%d",&n) != EOF){
cnt = 0;
for(int i = 1;i <= n;i ++)
scanf("%d",&a[i]);
BottomUpSort(a,1,n, b);
printf("%I64d\n",cnt);
}
return 0;
}