Data structure Merge sort-inverse number pair

Source: Internet
Author: User

Reverse order refers to a series of a[1],a[2],a[3] ... Any two numbers in A[i],a[j] (i<j), if A[I]>A[J], then we say that these two numbers constitute an inverse pair.


While merging the sorted two permutations of the process

The elements of the ordered sequence on the right are inserted sequentially into the preceding sequential sequence.

E.G. (3 7 12) (5 6 8)

Insert 5 in (3 7 12)

Because the back is ordered, it assumes that all elements of 5 and left are in reverse order, so there are mid+1.

And the left sequence has start1 number than 5, so the reverse number is Mid+1-start1

This can greatly reduce the time to calculate the inverse number pairs.


#include <iostream> #include <cstdio> #include <cstring>using namespace Std;int a[500005],b[500005];    Long long ans;void merge (int left,int mid,int right) {int start1=left,start2=mid+1;    int num=left;    int i; while (start1<=mid&&start2<=right) {if (A[start1]>a[start2]) {Ans=ans+mid-sta            rt1+1;        B[num++]=a[start2++];    } else b[num++]=a[start1++];    } while (Start1<=mid) b[num++]=a[start1++];    while (Start2<=right) b[num++]=a[start2++];    for (i=left; i<=right; i++) a[i]=b[i]; return;}    void mergesort (int left,int right) {int mid= (left+right)/2;        if (left<right) {mergesort (left,mid);        MergeSort (Mid+1,right);    Merge (Left,mid,right); } return;    int main () {int n;        while (~SCANF ("%d", &n)) {ans=0;                   for (int i=1; i<=n; i++) scanf ("%d", &a[i]); MErgesort (1,n);    printf ("%lld\n", ans); } return 0;}




Data structure Merge sort-inverse number pair

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.