P1908逆序对-java题解-归并排序

P1908逆序对-java题解-归并排序_第1张图片

        说实话,这道题用归并排序的话,完完全全就是模板稍微改动一点。不过我们需要反向求解,假设ai>aj,i


import java.io.*;
import java.util.*;

public class Main {
    static int[] b;
    static long ans;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StreamTokenizer st = new StreamTokenizer(br);
        PrintWriter pr = new PrintWriter(System.out);
        st.nextToken();int n=(int)st.nval;
        int[] a=new int[n+1];b=new int[n+1];
        for(int i=1;i<=n;i++){
            st.nextToken();
            a[i]=(int)st.nval;
        }
        msort(a,1,n);
        System.out.println(ans);
        pr.flush();
    }
    static void msort(int[] a,int l,int r){
        //归并排序模板+一点点的改动
        if(l>=r)return;
        int mid=l+r>>1,i=l,j=mid+1,k=i;
        msort(a,l,mid);msort(a,mid+1,r);
        while(i<=mid&&j<=r){
            if(a[i]<=a[j]) b[k++]=a[i++];
            else {
                b[k++]=a[j++];
                ans+=mid-i+1;
            }
        }
        while(i<=mid)b[k++]=a[i++];
        while(j<=r)b[k++]=a[j++];
        for(int z=l;z<=r;z++)
            a[z]=b[z];
    }
}

你可能感兴趣的:(洛谷-java题解,算法,java)