【hiho39】二分·歸併排序之逆序對,hiho39歸併逆序

來源:互聯網
上載者:User

【hiho39】二分·歸併排序之逆序對,hiho39歸併逆序

最近申請了微軟的暑假實習,4號就要線上筆試了,線上測試系統用的是http://hihocoder.com/,今天試手做了一道題。

【題目】

原題連結:http://hihocoder.com/contest/hiho39/problem/1 

輸入

第1行:1個整數N,表示數組長度。
第2行:N個整數,表示數組的元素a[i],1≤a[i]≤2^31-1。

輸出

第1行:1個整數,表示有多少對元素滿足a[i]>a[j],i<j。

範例輸入
101559614248 709366232 500801802 128741032 1669935692 1993231896 369000208 381379206 962247088 237855491
範例輸出
27

【Java代碼】

import java.util.Scanner;import java.math.BigInteger;public class Main {    //public int ans = 0;    public BigInteger ans = BigInteger.ZERO;        public void mergeSort(int[] a, int l, int r) {        if (l >= r) return;        int mid = (l + r) >> 1;        mergeSort(a, l, mid);        mergeSort(a, mid + 1, r);        merge(a, l, mid, r);    }        public void merge(int[] a, int l, int mid, int r) {        int[] b = new int[r - l + 1];        int i = l, j = mid + 1, k = 0;        while (i <= mid && j <= r) {            if (a[i] <= a[j]) {                b[k++] = a[i++];            } else {                //ans += mid - i + 1;                ans = ans.add(new BigInteger(String.valueOf(mid - i + 1)));                b[k++] = a[j++];            }        }        while (i <= mid) {            b[k++] = a[i++];        }        while (j <= r) {            b[k++] = a[j++];        }        i = l;        j = 0;        while (i <= r) {            a[i++] = b[j++];        }    }        public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int N = in.nextInt();        int[] a = new int[N];        for (int i = 0; i < N; i++) {            a[i] = in.nextInt();        }                Main m = new Main();        m.mergeSort(a, 0, N - 1);                //System.out.println(m.ans);        System.out.println(m.ans.toString());    }}

代碼中注釋部分是第一次提交的代碼,得分為80/100,看討論得知是int會溢出,所以換成BigInteger。

Tips:像這種部分test case通不過時,就要考慮大數溢出的情況。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.