求逆序数

用归并排序求逆序数。
http://blog.csdn.net/dlengong/article/details/7594919
http://blog.csdn.net/sevenmit/article/details/9081831
 
#include<stdio h="">
#include<string h="">
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
int a[1000005];
int b[1000005];
long long ans;
void m(int a[],int first,int mid,int last)
{
    int i=first,j=mid+1;
    int cur=first;
    while(i<=mid&&j<=last)
    {
        if(a[i]<=a[j])
        {
         b[cur++]=a[i++];
        }
        else
        {
            ans+=(j-cur);
            b[cur++]=a[j++];
        }
    }
    while(i<=mid)
    {
        b[cur++]=a[i++];
    }
    while(j<=last)
    {
        b[cur++]=a[j++];
    }
    for(int i=first;i<=last;i++)
    {
        a[i]=b[i];
    }
}
void msort(int a[],int first,int last)
{
    if(first==last)
        return;
    int mid=(first+last)/2;
    msort(a,first,mid);
    msort(a,mid+1,last);
    m(a,first,mid,last);
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        for(int i=1;i<=n;i++)
            cin>>a[i];
            ans=0;
            msort(a,1,n);
        cout<<ans<<endl;
    }
}

posted @ 2017-05-20 15:49  _大美  阅读(120)  评论(0编辑  收藏  举报