Martial Arts Tournament (Codeforces 1626D)
Tags: Greedy, binary search

Monocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.In particular, that implies that the number of participants in each division should be a power of two. Additionally, each division should have a non-zero amount of participants.$$$n$$$ participants have registered for the tournament so far, the $$$i$$$-th of them weighs $$$a_i$$$. To split participants into divisions, Monocarp is going to establish two integer weight boundaries $$$x$$$ and $$$y$$$ ($$$x < y$$$). All participants who weigh strictly less than $$$x$$$ will be considered lightweight. All participants who weigh greater or equal to $$$y$$$ will be considered heavyweight. The remaining participants will be considered middleweight.It's possible that the distribution doesn't make the number of participants in each division a power of two. It can also lead to empty divisions. To fix the issues, Monocarp can invite an arbitrary number of participants to each division.Note that Monocarp can't kick out any of the $$$n$$$ participants who have already registered for the tournament.However, he wants to invite as little extra participants as possible. Help Monocarp to choose $$$x$$$ and $$$y$$$ in such a way that the total amount of extra participants required is as small as possible. Output that amount.

Input: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases.The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of the registered participants.The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the weights of the registered participants.The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Output: For each testcase, print a single integer — the smallest number of extra participants Monocarp is required to invite after he chooses the weight boundaries $$$x$$$ and $$$y$$$.

Note: In the first testcase of the example, Monocarp can choose $$$x=2$$$ and $$$y=3$$$. Lightweight, middleweight and heavyweight divisions will have $$$2$$$, $$$1$$$ and $$$1$$$ participants, respectively. They all are powers of two, so no extra participants are required.In the second testcase of the example, regardless of the choice of $$$x$$$ and $$$y$$$, one division will have $$$1$$$ participant, the rest will have $$$0$$$. Thus, Monocarp will have to invite $$$1$$$ participant into both of the remaining divisions.In the third testcase of the example, Monocarp can choose $$$x=1$$$ and $$$y=2$$$. Lightweight, middleweight and heavyweight divisions will have $$$0$$$, $$$3$$$ and $$$3$$$ participants, respectively. So an extra participant is needed in each division.In the fourth testcase of the example, Monocarp can choose $$$x=8$$$ and $$$y=9$$$. Lightweight, middleweight and heavyweight divisions will have $$$8$$$, $$$0$$$ and $$$0$$$ participants, respectively. Middleweight and heavyweight division need an extra participant each.

Sample Inputs:
4
4
3 1 2 1
1
1
6
2 2 2 1 1 1
8
6 3 6 3 6 3 6 6

Sample Outputs:
0
2
3
2

Solution (Python):
def solvex(w):
    n = len(w)
    if n == 1:
        return 2
    w.sort()
    g = []
    last = 0
    for i in range(1, n):
        if w[i - 1] != w[i]:
            g.append(i - last)
            last = i
    g.append(n - last)
    print(g)
    print(w)
    minpow2 = 1 << n.bit_length() - 1
    if n > minpow2:
        minpow2 *= 2
    min_sol = minpow2 + 1 + 1
    sol = [minpow2, 1, 1]
    while minpow2 > 1:
        searchPow = minpow2 / 2
    print(min_sol)
    return 0

def findBorder(v, i1, i2, x):
    if v[i1] >= x:
        return i1
    if v[i2 - 1] < x:
        return i2
    while 1:
        k = (i1 + i2 - 1) // 2
        if k == i1:
            return i2 - 1
        if v[k] >= x:
            i2 = k + 1
        else:
            i1 = k

def searchVal(v, start, a, b):
    i = findBorder(v, start, len(v), a)
    if i == len(v):
        return false
    return a <= v[i] <= b

def calcCumulativa(w):
    cumulativa = []
    gruppi = []
    i = 1
    c = 1
    u = 0
    l = w[0]
    n = len(w)
    while i < n:
        if w[i] != l:
            u += c
            cumulativa.append(u)
            gruppi.append(c)
            c = 1
            l = w[i]
        else:
            c += 1
        i += 1
    u += c
    cumulativa.append(u)
    gruppi.append(c)
    return (gruppi, cumulativa)

def organizzaDueGironi(cu, start, giaPresi):
    if len(cu) - start == 0:
        return 2
    n = cu[-1] - giaPresi
    m = 1 << n.bit_length() - 1
    if n == m:
        if len(cu) - start == 1:
            return 1
        if searchVal(cu, start, n // 2 + giaPresi, n // 2 + giaPresi):
            return 0
        return 1
    n1 = n - m
    m1 = 1 << n1.bit_length() - 1
    if n1 == m1:
        pass
    else:
        m1 *= 2
    minore = 2 * m + 1 - n
    if len(cu) - start == 1:
        return minore
    while 1:
        if searchVal(cu, start, n - m + giaPresi, m1 + giaPresi) or (m != n and searchVal(cu, start, n - m1 + giaPresi, m + giaPresi)):
            minore = min(minore, m + m1 - n)
        if m1 == m:
            break
        m1 *= 2
    return minore

def organizzaTreGironi(cu):
    minore = 1 + organizzaDueGironi(cu, 0, 0)
    for i in range(0, len(cu)):
        primoGruppo = cu[i]
        m = 1 << primoGruppo.bit_length() - 1
        mancantiPrimoGruppo = 0 if primoGruppo == m else 2 * m - primoGruppo
        if mancantiPrimoGruppo < minore:
            altriMancanti = organizzaDueGironi(cu, i + 1, cu[i])
            minore = min(minore, mancantiPrimoGruppo + altriMancanti)
    return minore

def solve(w):
    n = len(w)
    if n == 1:
        return 2
    w.sort()
    (gruppi, cumulativa) = calcCumulativa(w)
    return organizzaTreGironi(cumulativa)
n = int(input())
for i in range(n):
    input()
    (*w,) = map(int, input().split())
    print(solve(w))

Solution (Python):
import math

class Solution:

    def MAT(self, arr):
        n = len(arr)
        d = int(math.log2(n - 1) + 1)
        arr.sort()
        cw = [1]
        for i in range(1, n):
            if arr[i] == arr[i - 1]:
                cw[-1] += 1
            else:
                cw.append(1)
        sl = [0] * (d + 1)
        c = 0
        s = 0
        for i in cw:
            s += i
            while s > 1 << c:
                c += 1
            sl[c] = s
        sr = [0] * (d + 1)
        c = 0
        s = 0
        for i in cw[-1::-1]:
            s += i
            while s > 1 << c:
                c += 1
            sr[c] = s
        ans = (1 << d) - n + 2
        for a in range(d):
            for b in range(d):
                lr = sl[a] + sr[b]
                c = 1
                while c < n - lr:
                    c <<= 1
                ans = min(ans, (1 << a) + (1 << b) + c - n)
        return ans
t = int(input())
ans = Solution()
for i in range(t):
    n = int(input())
    arr = [int(x) for x in input().split()]
    if n == 1:
        print(2)
    else:
        print(ans.MAT(arr))

Solution (Python):
import bisect
import collections
import random
import sys
p2D = lambda x: print(*x, sep='\n')

def II():
    return int(sys.stdin.buffer.readline())

def MI():
    return map(int, sys.stdin.buffer.readline().split())

def LI():
    return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
    return [LI() for _ in range(rows_number)]

def BI():
    return sys.stdin.buffer.readline().rstrip()

def SI():
    return sys.stdin.buffer.readline().rstrip().decode()

def li():
    return [int(i) for i in input().split()]

def lli(rows):
    return [li() for _ in range(rows)]

def si():
    return input()

def ii():
    return int(input())

def ins():
    return input().split()

def drank(d, processing, da, rank):
    tmp = 10 ** 9
    if len(d[da]) == 1:
        return 1
    for di in d[da]:
        if processing[di - 1] == 0:
            processing[di - 1] = 1
            tmp = min(tmp, drank(d, processing, di, rank))
            processing[di - 1] = 0
    rank[da - 1] = tmp + 1
    return tmp + 1

def binary_search(n, a):
    l = len(a)
    low = 0
    high = l - 1
    while high >= low:
        mid = (high + low) // 2
        if a[mid] == n:
            return mid
        elif a[mid] > n:
            high = mid - 1
        else:
            low = mid + 1
    return -1
import math

def solve():
    n = ii()
    a = li()
    a.sort()
    x = math.ceil(math.log(n, 2))
    ans = 1 + 1 + 2 ** x - n
    for i in range(x + 1):
        z = 2 ** i
        if z < n:
            k = z
            while k > 0 and a[k] == a[k - 1]:
                k -= 1
            y = n - k
            for j in range(math.ceil(math.log(y, 2)) + 1):
                tmp = z - k
                u = 2 ** j
                if u < y:
                    t = u
                    while t > 0 and a[t + k] == a[t - 1 + k]:
                        t -= 1
                    v = y - t
                    tmp += u - t + 2 ** math.ceil(math.log(v, 2)) - v
                    ans = min(ans, tmp)
                elif u == y:
                    tmp += 1
                    ans = min(ans, tmp)
        elif z == n:
            tmp = 2
            ans = min(ans, tmp)
    return ans

def main():
    for _ in range(ii()):
        sys.stdout.write(str(solve()) + '\n')
if __name__ == '__main__':
    main()