Candy Party (Hard Version) (Codeforces 1868B2)
Tags: Math, bitmasks

This is the hard version of the problem. The only difference is that in this version everyone must give candies to no more than one person and receive candies from no more than one person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.After Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.There will be $$$n$$$ people at the party. Initially, the $$$i$$$-th person has $$$a_i$$$ candies. During the party, they will swap their candies. To do this, they will line up in an arbitrary order and everyone will do the following no more than once:  Choose an integer $$$p$$$ ($$$1 \le p \le n$$$) and a non-negative integer $$$x$$$, then give his $$$2^{x}$$$ candies to the $$$p$$$-th person. Note that one cannot give more candies than currently he has (he might receive candies from someone else before) and he cannot give candies to himself. Daniel likes fairness, so he will be happy if and only if everyone receives candies from no more than one person. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.Determine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.

Input: The first line of input contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of people at the party.The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$) — the number of candies each person has.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

Output: For each test case, print "Yes" (without quotes) if exists a way to swap candies to make both Daniel and Tom happy, and print "No" (without quotes) otherwise.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.

Note: In the first test case, the second person gives $$$1$$$ candy to the first person, then all people have $$$3$$$ candies. In the second test case, the fourth person gives $$$1$$$ candy to the second person, the fifth person gives $$$2$$$ candies to the first person, the third person does nothing. And after the swaps everyone has $$$3$$$ candies.In the third test case, it's impossible for all people to have the same number of candies.In the fourth test case, the two people do not need to do anything.

Sample Inputs:
6
3
2 4 3
5
1 2 3 4 5
6
1 4 7 1 5 4
2
20092043 20092043
12
9 9 8 2 4 4 3 5 1 1 1 1
6
2 12 7 16 11 12

Sample Outputs:
Yes
Yes
No
Yes
No
Yes

Solution (Python):
for _ in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    su = sum(a)
    if su % n != 0:
        print('NO')
        continue
    sr = su // n
    step = [0] * 100
    voz1 = [0] * 100
    voz2 = [0] * 100
    for x in a:
        if x == sr:
            continue
        bx = str(bin(abs(x - sr)))[2:]
        f = bx.find('1')
        rf = bx.rfind('1')
        if bx[f:rf].count('0') != 0:
            print('NO')
            break
        if x > sr:
            step[len(bx) - f] += 1
            step[len(bx) - rf - 1] -= 1
            if rf == f:
                voz1[len(bx) - f - 1] += 1
        else:
            step[len(bx) - f] -= 1
            step[len(bx) - rf - 1] += 1
            if rf == f:
                voz2[len(bx) - f - 1] += 1
    else:
        if step.count(0) == 100:
            print('YES')
        else:
            for i in range(len(step)):
                if step[i] % 2 == 1:
                    print('NO')
                    break
                if step[i] > 0:
                    if voz2[i] * 2 < step[i]:
                        print('NO')
                        break
                    step[i + 1] += step[i] // 2
                elif step[i] < 0:
                    if voz1[i] * 2 < -step[i]:
                        print('NO')
                        break
                    step[i + 1] += step[i] // 2
            else:
                print('YES')

Solution (Python):
from math import log2

def l(n):
    v = log2(n)
    if v % 1 != 0:
        x = 0
        while n % 2 == 0:
            x += 1
            n = n // 2
        u = log2(n + 1)
        if u % 1 != 0:
            return -1
        else:
            return [1, x + int(u), x]
    else:
        return [2, int(v + 1), int(v)]
for t in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    verdict = 1
    k = sum(a) / n
    if k % 1 != 0:
        print('No')
    else:
        k = int(k)
        lst = [0] * 30
        DS = [0] * 30
        DT = [0] * 30
        for i in range(n):
            if a[i] - k != 0:
                u = l(abs(a[i] - k))
                if u == -1:
                    verdict = 0
                    break
                else:
                    if u[0] == 1 and a[i] > k:
                        lst[u[1]] += 1
                        lst[u[2]] -= 1
                    if u[0] == 1 and a[i] < k:
                        lst[u[2]] += 1
                        lst[u[1]] -= 1
                    if u[0] == 2 and a[i] > k:
                        DS[u[2]] += 1
                    if u[0] == 2 and a[i] < k:
                        DT[u[2]] += 1
        if verdict == 0:
            print('NO')
        else:
            for i in range(29, 0, -1):
                lst[i] += DS[i] - DT[i]
                if lst[i] == 0:
                    continue
                elif lst[i] < 0:
                    if abs(lst[i]) > DS[i - 1]:
                        verdict = 0
                        break
                    else:
                        DS[i - 1] -= abs(lst[i])
                        lst[i - 1] -= abs(lst[i])
                elif DT[i - 1] < lst[i]:
                    verdict = 0
                    break
                else:
                    DT[i - 1] -= lst[i]
                    lst[i - 1] += lst[i]
            if verdict == 0:
                print('NO')
            elif lst[0] + DS[0] - DT[0] == 0:
                print('YES')
            else:
                print('NO')

Solution (Python):
import sys

def input_fn():
    return sys.stdin.readline().strip()

def decompose(a):
    aux = None
    flg = a < 0
    a = abs(a)
    ret = [0, 0]
    while a % 2 == 0:
        ret[0] += 1
        a //= 2
    a += 1
    ret[1] = ret[0]
    while a % 2 == 0:
        ret[1] += 1
        a //= 2
    if a != 1:
        return (None, None)
    if ret[1] == ret[0] + 1:
        aux = [flg, ret[0]]
    if flg:
        ret = ret[::-1]
    return (ret, aux)

def solve():
    n = int(input_fn())
    A = list(map(int, input_fn().split()))
    if sum(A) % n:
        return 'No'
    target = sum(A) // n
    pool = [0 for i in range(32)]
    auxes = []
    for i in A:
        if target == i:
            continue
        (temp, aux) = decompose(target - i)
        if temp is None:
            return 'No'
        pool[temp[0]] += 1
        pool[temp[1]] -= 1
        if aux is not None:
            auxes.append(aux)
    auxes = sorted(auxes, key=lambda i: i[1])
    for aux in auxes:
        if pool[aux[1]] == 0:
            continue
        elif aux[0] ^ (pool[aux[1]] > 0):
            pool[aux[1]] += (aux[0] * 2 - 1) * 2
            pool[aux[1] + 1] -= aux[0] * 2 - 1
    for i in range(32):
        if pool[i] != 0:
            return 'No'
    return 'Yes'
T = int(input_fn())
for i in range(T):
    print(solve())