Here is the correct code
#include<stdio.h>
#include<stdlib.h>
int main() {
int t,T,n,i,j;
long long int count,k;
scanf("%d",&T);
int *c = calloc(1000000,sizeof(int));
for(t=0;t<T;t++){
scanf("%d",&n);
int temp;
count =0;
for(i=0;i<n;i++){
scanf("%d",&temp);
c[temp-1]++ ;
}
for(i=0;i<1000000;i++){
if(c[i]>1){
k = c[i];
count+= k*(k-1);
}
c[i] = 0;
}
printf("%lld\n",count);
}
return 0;
}
Changes :
- Used
callocto initialize the array to zero (don’t know why, but your
method of array initialisation gives segmentation fault) - As the limit for
nis100000hence the output may be as high asn^2i.e.10000000000which out ofintrange, hence usedlong long intforcountvariable.
8
solved Why this code is not giving right result for large arrays? [closed]