int main(void) {
int t,l;
long double fact[51]={1};
scanf("%d",&t);
for(l=1;l<=50;l++)
fact[l]=l*fact[l-1];
while(t--)
{
int i,n,k,a[50],j,np=0,rp=0;
long sum=0;
long double ans=0;
scanf("%d %d",&n,&k);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(&a[0],0,n-1);
i=k-1;
while(i>0 && a[i]==a[i-1])
i--;
rp=k-i;//i will be the starting pos of last unique number
i=k-1;
while(i<(n-1) && a[i]==a[i+1])
i++;
np=rp+(i-(k-1));
ans=fact[np]/(fact[rp]*fact[np-rp]);//calculate this
//printf("%.0Lf ",fact[30]);
printf("%.0Lf\n",ans);
}
return 0;
}
This is the code i tried. Now i know that using double will give precision errors in case of large factorials thus giving wrong factorial values, but to my surprise the solution got accepted for all cases. I want to know why this happened? I mean how the nCr formula produced correct answer even for wrong values of factorial
Do you think the proposed solution will work for an already sorted original sequence?
The above solution works just fine for a randomly distributed original sequence but I can’t seem to wrap my head around for the case when the original sequence is already sorted.
Please help by explaining.
EDIT
I got it now. Even if the values of elements are same they are considered distinct.
One thing that’s wrong is that you are eraseing an iterator (thus invalidating it) and then continuing to use that iterator, which is Undefined Behaviour.
Although I checked with all possible cases I can think of, I still get the Wrong Answer with this code. Please help me to look for its mistakes.
#include<stdio.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(void)
{
int T,N,K;
int A[50];
int i,f,j,l;
int count,ans;
scanf("%d",&T);
for ( i = 0 ; i < T ; i++)
{
scanf("%d %d",&N,&K);
for ( f = 0 ; f < N ; f++)
{
scanf("%d",&A[f]);
}
qsort (A, N, sizeof(int), compare);
count = 1;
for ( j = 0 ; j < N - 1 ; j++)
{
if ( A[j]== A[j+1])
{
count++;
}
else
{
break;
}
}
if ( count <= K)
{
ans = 1;
}
else
{
ans = 0;
for ( l = 0 ; l < count ; l++)
{
ans += l;
}
}
printf("%d\n",ans);
}
return 0;
}
Is it necessary to scan using scanf instead of cin and print using printf instead of cout? If yes why? If not so, then why it is wrong answer each time?