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. Please tell me my mistake.
problem link: 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);
}