Monk loves cakes! He visits the Binary Bakery to buy some of his favorite cheesecakes.…
- User
Monk loves cakes! He visits the Binary Bakery to buy some of his favorite cheesecakes.
The owner of the bakery, Bob, is a clever man. He does not want Monk to finish all his cheesecakes. Hence, he plays a game. The Monk is given N numbers and has to select K of these numbers. For each number that Monk chooses, he will get as many cheesecakes as the number of 1's in the Binary representation of the number i.e. the number of bits that are set. Help Monk find the maximum number of cakes that he can have. Input: The first line of input contains T. T test cases follow. First line of each test cases contains 2 space-separated integers N and K. The next line contains N space-separated integers.Output: For each test cases, print the answer in a new line.
Constraints: 1 ≤ T ≤ 10 1 ≤ N ≤ 10^3 0 ≤ K ≤ N 0 ≤ Numbers ≤ 10^5
SAMPLE INPUT 1 4 2 6 1 2 0
SAMPLE OUTPUT 3
Explanation
He chooses numbers 6 (110) and 1 (001) with 2 and 1 set bits respectively.
Assistant
We need to write a solution to the problem: given N numbers, select K numbers to maximize sum of set bits (popcount). Since we can choose any K numbers, we should simply pick the K numbers with the largest popcounts. Because each number's contribution is its number of set bits (which is independent and additive). So we compute popcount for each number, sort descending, sum top K.
Constraints small: N up to 1000, numbers up to 100000 (popcount up to 17). T up to 10.
We need to write code. Possibly the problem is from HackerEarth, typical.
Implementation: read T, loop. For each test case: read N and K, read list of N integers. Compute list of popcounts. Then sort descending, sum first K. Print sum.
Edge cases: K could be 0, sum zero. Numbers could be 0, popcount 0.
Write popcount efficiently: built-in bin(x).count('1') is fine. Or use bit_count in Python 3.8+? Actually Python 3.10+ has int.bit_count() but to be safe, use bin.
Complexity: O(N log N) per test case.