I saw this program on Codechef.
There are N packets each containing some candies. (Eg: 1st contains 10, 2nd contains 4 and so on)
We have to select exactly M packets from it ( M<=N) such that total candies are divisible by K.
If there are more than one solution then output the one having lowest number of candies.
I thought its similar to Subset Sum problem but that is NP hard. So it will take exponential time.
I don’t want the complete solution of this program. An algorithm would be appreciated. Thinking on it from 2 days but unable to get the correct logic.
1 ≤ M ≤ N ≤ 50000, 1 ≤ K ≤ 20
Number of Candies in each packet [1,10^9]
Let
packetscontain the original packets.Partition
kinto sums ofp = 1, 2, ..., mnumbers>= 1and< k(there areO(2^k)such partitions). For each partition, iterate overpacketsand add those numbers whose remainder modulokis one of the partition’s elements, then remove that element from the partition. Keep the minimum sum as well, and update a global minimum. Note that ifm > p, you must also havem - pzeroes.You might be thinking this is
O(2^k * n)and it’s too slow, but you don’t actually have to iterate thepacketsarray for each partition if you keepnum[i] = how many numbers have packets[i] % k == i, in which case it becomesO(2^k + n). To handle the minimum sum requirement too, you can keepnum[i] = the list of the numbers that have packets[i] % k == i, which will allow you to always pick the smallest numbers for a valid partition.