Reverse order pairs

Posted lym11248

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Reverse order pairs相关的知识,希望对你有一定的参考价值。

In a sequence of numbers,we can find some number pairs that conform to the rule below:

Assuming that there exist two numbers,N and M and it‘s position in the sequence is n and m.

If the value of N is greater than M and n is less than m,we define the pair as "Reverse order pair".

So,try to find out all pairs in a sequence quickly.

 

Input:

5

5 2 1 3 4

 

Output:

5

 

S:

Of cause we can enumerate all the sequence.

But there is a better solution using the trait of merge sort.

Complete code is given below:

#include<iostream>
using namespace std;

int t[1000],a[1000];
int ans=0;
void mmerge(int ll, int rr) {
    if(ll==rr) return;
    else{
        int mid=(ll+rr)/2;
        mmerge(ll,mid);
        mmerge(mid+1,rr);
        int s=ll,q=ll,p=mid+1;
        while(s<=rr){
            if(q>mid||(p<=rr&&a[p]<a[q])){
                for(int m=q;m<=mid;m++)
                    cout<<"{"<<a[m]<<","<<a[p]<<"}"<<endl;
                t[s++]=a[p++];
          ans+=mid-q+1;
          //if the a[p] is less than a[q] it means that a[q]...a[mid] all greater than a[p]. }
else t[s++]=a[q++]; } for(int i=ll;i<=rr;i++) a[i]=t[i]; } } int main(){ int N; cin>>N; for(int i=0;i<N;i++){ cin>>a[i]; } mmerge(0,N-1); cout<<endl<<ans; return 0; }

Why does it work?

Because finding the pairs don‘t need the position of numbers.You don‘t have to maintain the position.

For example:

"52134" the reverse order pair of 1 are {5,1},{2,1},you can just make the judgment by the value of the number.Position is not cared.

"25134"----->{2,1},{5,1}.

So we can separate the sequence into groups.At first we count in small groups,then the larger groups.

In oder to compare the numbers,we sort the group in every layer.

Dichotomy+sort+merge=merge_sort.

以上是关于Reverse order pairs的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 493. Reverse Pairs

Reverse Pairs

493. Reverse Pairs

LeetCode 493. Reverse Pairs

LeetCode -Reverse Pairs

[LeetCode] Reverse Pairs 翻转对