Problem: 2061D - Kevin and Numbers
Language: python

Solution 1 (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()

Solution 2 (runtime: 640 ms):
import sys

import string

import math

import array

import bisect

from heapq import heappop,heappush

from functools import lru_cache,cache

from collections import deque,defaultdict,Counter

from itertools import permutations,combinations

#sys.setrecursionlimit(10**5)

input = sys.stdin.readline

printf = lambda x:sys.stdout.write(x)



INF = 10**15



RI = lambda: int(sys.stdin.readline())

RF = lambda: float(sys.stdin.readline())

RS = lambda: sys.stdin.readline().strip()

RFF = lambda: map(float, sys.stdin.readline().split())

RII = lambda: map(int, sys.stdin.readline().split())

RSS = lambda: map(str, sys.stdin.readline().strip().split())

RIL = lambda: list(RII())

RFL = lambda: list(RFF())

RSL = lambda: list(RSS())



from types import GeneratorType

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        if stack:

            return f(*args, **kwargs)

        else:

            to = f(*args, **kwargs)

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        break

                    to = stack[-1].send(to)

            return to



    return wrappedfunc



def main():

    test = RI()

    

    for i in range(test):

        n,m = RII()

        a = RIL()

        b = RIL()

        #db = Counter(b)

        #a.sort()

        da = Counter([str(i) for i in a])

        

        # @bootstrap

        # def dp(i):

        #     if i==1:

        #         da[i] -= 1

        #         yield None

        #     if da[i]>=1:

        #         da[i] -= 1

        #         yield None

        #     x = i//2

        #     y = x+i%2

        #     yield dp(x)

        #     yield dp(y)

        #     yield None

        cnt = 0

        @bootstrap

        def dp(i):

            nonlocal cnt

            if cnt>=n:

                da[str(0)] -= 1

                yield None

            if i==1:

                da[str(i)] -= 1

                cnt += 1

                yield None

            if da[str(i)]>=1:

                da[str(i)] -= 1

                cnt += 1

                yield None

            x = i//2

            y = x+i%2

            yield dp(x)

            yield dp(y)

            yield None

        

        for i in b:

            dp(i)

        #print(da)

        flag = True

        for x in da.values():

            if x!=0:

                flag = False

                break

        

        if flag==True:

            print('Yes')

        else:

            print('No')    





if __name__ == '__main__':

    main()