Problem: 2061D - Kevin and Numbers
Language: python

Solution 1 (runtime: 656 ms):
from random import randint
class MyDict:
    def __init__(self, func=lambda: 0):
        self.random = randint(0, (1 << 32) - 1) 
        self.default = func
        self.dict = {}
    def _hash(self, key):
        return self.random ^ hash(key)
    def __getitem__(self, key):
        mykey = self._hash(key)
        if mykey not in self.dict:
            self.dict[mykey] = self.default()
        return self.dict[mykey]
    def __setitem__(self, key, value):
        self.dict[self._hash(key)] = value
    def __delitem__(self, key):
        mykey = self._hash(key)
        if mykey in self.dict:
            del self.dict[mykey]
        else:
            raise KeyError(key)
    def get(self, key, default=None):
        return self.dict.get(self._hash(key), default)
    def keys(self):
        return [self._hash(k) for k in self.dict]
    def values(self):
        return self.dict.values()
    def items(self):
        return [(self._hash(k), v) for k, v in self.dict.items()]
    def __contains__(self, key):
        return self._hash(key) in self.dict
    def __iter__(self):
        return iter(self.keys())
    def __len__(self):
        return len(self.dict)
    def __str__(self):
        return str({self._hash(k): v for k, v in self.dict.items()})
    def __repr__(self):
        return f"MyDict({self.default}, {self.dict})"

import heapq
def solve():
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))

    st = []
    for i in b :
        st.append(-i)

    heapq.heapify(st)

    freq = MyDict()
    for i in a:
        freq[i] += 1

    for i in range(2*n-m):
        if not st:
            print("NO")
            return
        val = - heapq.heappop(st)
        if freq[val] != 0:
            freq[val] -= 1

        else:
            heapq.heappush(st,-(val // 2))
            heapq.heappush(st,-((val+2-1)//2))
    if st :
        print("NO")
    else:
        print("YES")

for __ in range(int(input())):
    solve()

Solution 2 (runtime: 702 ms):
import heapq

import sys



# Use fast I/O

readline = sys.stdin.readline



def solve():

    """

    Solves a single test case for the Kevin and Numbers problem.

    Reads the sequences A and B, checks if A can be transformed into B

    using the specified operation, and prints "Yes" or "No".



    The core idea is to simulate the process in reverse. We start with sequence B

    and apply the reverse operation: split an integer `z` into two integers `x, y`

    such that `z = x+y` and `|x-y| <= 1`. This splitting rule is deterministic:

    - If `z` is even and `z >= 2`, it splits into `z/2, z/2`.

    - If `z` is odd and `z >= 3`, it splits into `(z-1)/2, (z+1)/2`.

    - `z=1` cannot be split into two positive integers satisfying the condition.

    

    We want to know if we can reach sequence A after exactly N-M splits starting from B.

    We use max heaps to manage the elements and greedily match or split the largest elements.

    Max heaps are implemented using Python's `heapq` module (which provides min heaps)

    by storing negative values.

    """

    N, M = map(int, readline().split())

    A = list(map(int, readline().split()))

    B = list(map(int, readline().split()))



    # A necessary condition for the transformation is that the sum of elements must be invariant.

    # The operation replaces x, y with x+y, changing the total sum by (x+y) - (x+y) = 0.

    # This appears wrong, the operation removes two numbers x,y and adds one number x+y.

    # The sum changes from S to S - x - y + (x+y) = S. The sum IS invariant.

    if sum(A) != sum(B):

        print("No")

        return



    # Initialize max heap for the target sequence A. Stores -x for each x in A.

    pq_a = [-x for x in A]

    heapq.heapify(pq_a)

    

    # Initialize max heap for the current sequence, starting with B. Stores -x for each x in B.

    # Elements in pq_b will be split progressively.

    pq_b = [-x for x in B]

    heapq.heapify(pq_b)



    # Process elements using the heaps. Continue as long as there are elements in B's heap.

    while pq_b:

        # Pop the largest element from B's current representation (-ve value from min-heap).

        top_b_neg = heapq.heappop(pq_b)

        top_b = -top_b_neg # Convert back to positive value



        # Check if A's heap is empty. If so, all elements of A have been matched/accounted for.

        # If B's heap still has elements (like top_b we just popped), it indicates a mismatch.

        # The sums matched initially, so this state means B's structure requires more elements

        # or different elements than A provides.

        if not pq_a:

             print("No")

             return



        # Peek the largest element currently required by A (target sequence).

        top_a_neg = pq_a[0]

        top_a = -top_a_neg



        # If the largest element available from B's transformation (top_b) is smaller than

        # the largest element required by A (top_a), then it's impossible to form A.

        # The reverse splitting process only generates numbers less than or equal to the parent.

        if top_b < top_a:

            print("No")

            return



        # If the largest elements match (top_b == top_a), it signifies that this element `top_a`

        # from A corresponds to `top_b` derived from B (potentially after some splits).

        # We consume `top_a` by popping it from A's heap.

        if top_b == top_a:

            heapq.heappop(pq_a)

            # Continue to the next largest element in B's heap.

            continue 



        # Case: top_b > top_a

        # The element `top_b` is larger than the current target `top_a`.

        # This implies `top_b` must have been formed by a sum operation in the forward process.

        # We reverse this by splitting `top_b` into its unique constituents (x, y) based on the rules.

        

        # An element of 1 cannot be split into two positive integers satisfying the rules.

        # If top_b is 1, it must match top_a == 1. This would be handled by the `top_b == top_a` case.

        # Reaching this point (`top_b > top_a`) with top_b=1 is logically impossible

        # because the smallest possible value for top_a is 1.

        if top_b == 1:

             # Include this check for logical consistency, though it should not be reached.

             print("No") 

             return



        # Perform the split based on the parity of top_b.

        # The rules ensure children x, y are positive integers.

        if top_b % 2 == 0:

            # Even number z (>= 2) splits into z/2, z/2.

            x = top_b // 2

            y = top_b // 2

        else: 

            # Odd number z (>= 3) splits into (z-1)/2, (z+1)/2.

            x = top_b // 2 

            y = top_b // 2 + 1

            

        # Add the two resulting numbers (children) back into B's heap.

        # Store them as negative values for the max heap simulation.

        heapq.heappush(pq_b, -x)

        heapq.heappush(pq_b, -y)

        

    # After the loop finishes, B's heap (pq_b) is empty.

    # For a valid transformation, A's heap (pq_a) must also be empty at this point.

    # This means all elements required by A have been matched.

    if not pq_a:

        # Both heaps are empty. The transformation is possible.

        print("Yes")

    else:

        # B's heap is empty, but A still requires elements. Mismatch.

        print("No")



# Read the number of test cases from standard input.

T = int(readline())

# Process each test case by calling the solve function.

for _ in range(T):

    solve()