Hi everybody, I got this question from an online competition... i tried to solve it
But i am getting "TIMED OUT ERROR"...
The problem is...I have N packets of candy ...out of which i have to distribute k packets of candy to each person such that unfairness is minimised...
Suppose the K packets have (x1, x2, x3,….xk) candies in them, where xi denotes the number of candies in the ith packet, then we define unfairness as
sigma(Xi-Xj) = abs(a) where 1
<j><k>
where |a| denotes the absolute value of a.
constraints 2 < N < 10 pow 5
2<= K <= N
0 <= no.of packets in each candy <= 10 pow 9
Sample Input :
N = 7
K = 3
packets = 10 100 300 200 1000 20 30
Sample Output :
40
Explanation :
I will choose packets having 10, 20 and 30 candies.So unfairness will be |10-20| + |20-30| + |30-10| = 40. It will be minimum as compared to any other distribution which can be verified
Thia is my code.... It runs fine..the problem is it takes too much time for large no. of inputs upto (10 pow 5)... I want to know how to optimize it...
this is the code...
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void quicksort(long int [100000],long int,long int);
int main()
{
long int packs[100000],n,k,i,j;
long int key1=0,key2 = 999999999;
long int temp = 999999999 ;
long int l;
scanf("%ld",&n);
scanf("%ld",&k);
for(i=0;i<n;i++)
scanf("%ld",&packs[i]);
quicksort(packs,0,n-1);
for(i=0;i<(n-k);i++)
{
for(j=i;j<(k-1+i);j++)
{
for(l=j+1;l<=(k-1+i);l++)
{
key1 += abs(packs[j]-packs[l]);
}
}
if( key1 < temp)
key2 = temp = key1;
key1 = 0;
}
printf("%ld",temp);
return 0;
}
I tried reducing the loops...so i did this...the sum of the previous sequence is used to calculate the next sequence....
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void quicksort(long int [100000],long int,long int);
long int main()
{
long int packs[100000],n,k,i,j;
long int key1 = 0,key2 = 0;
long int temp = 0 ;
long int l,m;
scanf("%ld",&n);
scanf("%ld",&k);
for(i=0;i<n;i++)
packs[i] = random(1000000);
quicksort(packs,0,n-1);
for(l=0;l<k;l++)
for(m=l;m<k;m++)
{
key1 = temp += abs(packs[l] - packs[m]);
}
for(i=1;i<(n-k);i++)
{
for(j=i;j<(k+i-1);j++)
{
key1 += abs(packs[j] - packs[k+i-1]);
key2 += abs(packs[j] - packs[i-1]);
}
key1 = key1-key2 ;
if( key1 < temp)
temp = key1;
key2 = 0;
}
printf("%ld",temp);
return 0;
}
But in this code i am getting the error as "WRONG ANSWER" when i submit it ,in the website's compiler...