codevs.1688 求逆序對

題目描述 Description

給定一個序列a1,a2,…,an,如果存在i<j並且ai>aj,那麼我們稱之爲逆序對,求逆序對的數目

 

數據範圍:N<=105Ai<=105。時間限制爲1s。


輸入描述 Input Description

第一行爲n,表示序列長度,接下來的n行,第i+1行表示序列中的第i個數。

輸出描述 Output Description

所有逆序對總數.

樣例輸入 Sample Input

4

3

2

3

2

樣例輸出 Sample Output

3

數據範圍及提示 Data Size & Hint

直接歸併排序求逆序數

代碼如下:
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<iomanip>
using namespace std;
const int maxn = 100050;
long long int ans=0;
void merge_sort(long long *a,int x,int y,long long *t);
int main(){
   //freopen("Text.txt","r",stdin);
   int n,x;
   long long a[maxn],t[maxn];
   cin>>n;
   for(int i=1;i<=n;i++){
       cin>>x;
       a[i]=x;
   }
   merge_sort(a,1,n,t);
   /*for(int i=1;i<=n;i++)
   cout<<t[i]<<ends;
   cout<<endl;*/
   cout<<ans<<endl;
   return 0;
}
void merge_sort(long long *a,int x,int y,long long *t){
   if(x==y)return ;
   int m=(x+y)/2;
   int p=x,q=m+1,i=x;
   merge_sort(a,p,m,t);
   merge_sort(a,q,y,t);
   while(p<=m&&q<=y){
       if(a[p]>a[q]){
           ans+=m-p+1;
           t[i++]=a[q++];
       }
       else
          t[i++]=a[p++];
   }
   while(p<=m)t[i++]=a[p++];
   while(q<=y)t[i++]=a[q++];
   for(i=x;i<=y;i++)
      a[i]=t[i];
}


發佈了87 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章