hello ,iam trying to solve INVERSION COUNT problem on SPOJ , i am using merge sort
but still its saying TIME LIMIT EXCEEDED!!!
somebody pls help!!!
this is my code::
#include
#include<stdio.h>
using namespace std;
long merge(long num[],long l,long m,long r)
{
long long inv=0;
long n1,n2,i,j,k;
long *sub1=new long[300000];
long *sub2=new long[300000];
n1=(m-l)+1;
n2=r-m;
for(i=0;i<n1;i++) sub1[i]=num[i+l];
for(i=0;i<n2;i++) sub2[i]=num[i+m+1];
for(i=0,j=0,k=l;(i<n1 && j<n1);k++)
{
if(sub1[i]<=sub2[j])
{ num[k]=sub1[i];
i++;
}
else
{ inv=1;
num[k]=sub2[j];
inv+=(m-i);
j++;
}
}
while(i<n1)
{ num[k]=sub1[i];
i++; k++;
}
while(j<n2)
{ num[k]=sub2[j];
j++; k++;
}
delete[] sub1;
delete[] sub2;
return inv;
}
long mergesort(long num[],long l,long r)
{
long long inv=0;
if(l<r)
{ int m=(l+r)/2;
inv=mergesort(num,l,m);
inv+=mergesort(num,m+1,r);
inv+=merge(num,l,m,r);
}
return inv;
}
int main()
{
long t,n,i;
long long ans;
long *num = new long[300010];
scanf("%ld",&t);
while(t–)
{
scanf("%ld",&n);
for(i=0;i<n;i++) scanf("%ld",&num[i]);
ans=mergesort(num,0,n-1);
printf("%lld",ans); printf("\n");
}
return 0;
}