简体   繁体   English

计算数组中的反转数

[英]Counting number of inversions in an array

For the given problem statement we need to calculate the number of inversion in an array so i tried to apply an algorithm using merge sort and calculating the number of inversion while merging and also at time of sorting. 对于给定的问题陈述,我们需要计算数组中的求逆数,因此我尝试应用一种使用合并排序的算法,并在合并时以及排序时计算求逆数。 While my code gives the same answer for the test cases i fed to the system as my own solutions i am getting a wrong answer on the online judge - Codechef. 虽然我的代码对我送入系统的测试用例给出了与我自己的解决方案相同的答案,但在线法官Codechef却得到了错误的答案。 Please tell me my mistake. 请告诉我我的错误。

problem link: http://www.codechef.com/COOK43/problems/LPAIR 问题链接: http : //www.codechef.com/COOK43/problems/LPAIR

code: 码:

#include<iostream>
using namespace std;

long long int Merge(int* left,int* right,int* arr,int nl,int nr)
{
    int i=0;
    int j=0;
    int k=0;
    long long int cnt=0;
    while(i<nl&&j<nr)
    {
        if(left[i]<=right[j])
        {
            arr[k]=left[i];
            i++;
        }
        else
        {
            arr[k]=right[j];
            j++;
            cnt+=nl-i;
        }
        k++;
    }
    while(i<nl)
    {
        arr[k]=left[i];
        i++;
        k++;
    }
    while(j<nr)
    {
        arr[k]=right[j];
        j++;
        k++;
    }
    return cnt;
}

long long int MergeSort(int *a,int len)
{
    long long int cnt=0;
    if(len<2)
        return 0;
    int mid=len/2;
    int* left=new int[mid];
    int* right=new int[len-mid];
    for(int i=0;i<mid;i++)
        left[i]=a[i];
    for(int i=mid;i<len;i++)
        right[i-mid]=a[i];
    cnt+=MergeSort(left,mid);
    cnt+=MergeSort(right,len-mid);
    cnt+=Merge(left,right,a,mid,len-mid);
    delete(left);
    delete(right);
    return cnt;
}

int main()
{
    int n;
    cin>>n;
    int* fm=new int[n];
    for(int i=0;i<n;i++)
        cin>>fm[i]>>fm[i];
    cout<<MergeSort(fm,n);
}

This is the correct approach and you have a very simple problem - the number of inversions for n = 10 5 may overflow integer. 这是正确的方法,您有一个非常简单的问题-n = 10 5的求反数可能会溢出整数。 Think of how you can fix that. 想想如何解决这个问题。

The Error is input pairs of men and women will not given as sorted based on Male Chef Mi. 错误是不会根据男厨师米的排序给出男女输入对。

Before running merge sort you need to sort the pair based on Mi < Male number> because male should be standing in an increasing order. 在运行合并排序之前,您需要根据Mi <Male number>对对进行排序,因为male应该以递增的顺序站立。

so your array fm should be array of pairs and then sort this according to Mi. 因此您的数组fm应该是对数组,然后根据Mi对其进行排序。

And then all the operation in merge-sort will be based on second element of fm (fm.second) 然后,归并排序中的所有操作都将基于fm的第二个元素(fm.second)

Solution

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM