1019 逆序数

1019 逆序数

基准时间限制:秒 空间限制:131072 KB 

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。

2 4 3 1中,2 14 34 13 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。

Input

1行:NN为序列的长度(n <= 50000)

2 - N + 1行:序列中的元素(0 <= A[i] <= 10^9

Output

输出逆序数

Input示例

4

2

4

3

1

Output示例

4

import java.util.Scanner;
public class Main1 {
    static int a[];
    static int b[];
    static int count=0;
    static void Merger(int low,int mid,int high){
        int i,j,k;
        for(i=low,j=mid+1,k=0;i<=mid && j<=high;){
            if(a[i]<=a[j])
                b[k++]=a[i++];
            else
            {
                b[k++]=a[j++];
                count+=mid-i+1;
            }
        }
        while(i<=mid)
            b[k++]=a[i++];
        while(j<=high)
            b[k++]=a[j++];
        for(k=0;low<=high;low++,k++)
        {
            a[low]=b[k];
        }
        
    }
    
    static void Mersort(int low,int high){
        
        if(low==high)  return ;
        int mid=(low+high)/2;
        Mersort(low,mid);
        Mersort(mid+1,high);
        Merger(low,mid,high);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        int i,n;
        {
            count =0;n=sc.nextInt();
            a=new int[n+1];
            b=new int[n+1];
            for(i=0;i<n;i++)
                a[i]=sc.nextInt();
            Mersort(0,n-1);
            System.out.println(count);
            
            
        }
        sc.close();

    }

}
--------------------------
贴一组超时的算法。。。。
-------------------------------------
package 逆序对;
import java.util.Scanner;
public class Main {
    static int count(int a[]){
         int count=0;
         for(int i=0;i<a.length;i++){
             for(int j=i+1;j<a.length;j++){
                 if(a[i]>a[j])count++;
             }
         }
         return count;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            int n=sc.nextInt();
            int a[]=new int[n];
            for(int i=0;i<n;i++)
                a[i]=sc.nextInt();
                    System.out.println(count(a));
        }
        sc.close();

    }

}
原文地址:https://www.cnblogs.com/watchfree/p/5348673.html