1. 程式人生 > >poj2299--歸並排序求解逆序對

poj2299--歸並排序求解逆序對

HP poj stdio.h class long sum sort blank AI

1、題目鏈接

http://acm.hrbust.edu.cn/vj/index.php?c=problem-problem&id=166400

2、代碼:

//歸並排序求解逆序對 
#include<iostream>
#include<stdio.h> 
#include<math.h>
#include<algorithm>
#include<stack>
#include<queue>
#include<string.h>
typedef long long int ll; 
using
namespace std; ll n,sum; ll a[500005],temp[500005]; void Merge(ll a[],ll l,ll mid,ll r){ ll i=l,j=mid+1,k=0; while(i<=mid&&j<=r){ if(a[i]<a[j]){ temp[k++]=a[i++]; } else{ temp[k++]=a[j++]; sum+=mid-i+1;//求逆序對 } }
while(i<=mid) temp[k++]=a[i++]; while(j<=r) temp[k++]=a[j++]; for(ll i=l,k=0;i<=r;k++,i++) a[i]=temp[k]; } void MergeSort(ll a[],ll l,ll r){ ll mid; if(l<r){ mid=(l+r)/2; MergeSort(a,l,mid); MergeSort(a,mid+1,r); Merge(a,l,mid,r); } }
int main() { while(~scanf("%lld",&n)) { sum = 0; if(n == 0) break; for(int i = 0; i < n; i++) scanf("%lld",&a[i]); MergeSort(a,0,n-1); printf("%lld\n",sum); } return 0; }

poj2299--歸並排序求解逆序對