#!/bin/python3 import sys from collections import defaultdict, namedtuple State = namedtuple('State', ('current_zoo', 'unload_count', 'E', 'D', 'C', 'M')) def minimumZooNumbers(m, n, t, s, d): # Return a list of length n consisting of the answers zoos_in = [defaultdict(int) for _ in range(m)] zoos_out = [defaultdict(int) for _ in range(m)] active_zoo = [False] * m for i, animal, source, dest in zip(range(m), t, s, d): zoos_in[source-1][animal] |= 1 << i zoos_out[dest-1][animal] |= 1 << i active_zoo[source-1] = True active_zoo[dest-1] = True intial_state = State(-1, 0, 0, 0, 0, 0) parent = {intial_state: None} unload_tracker = [float('inf')] * n def dfs_visit(s): # print('visiting %s %s %s %s %s %s' % (s.current_zoo, s.unload_count, s.E, s.D, s.C, s.M)) for i in range(s.current_zoo + 1, m): if not active_zoo[i]: continue unload_count = s.unload_count animal_types = {'E': s.E, 'D': s.D, 'C': s.C, 'M': s.M} # Unload the animals that are at destination for animal_type, animals in animal_types.items(): animals_at_dest = animals & zoos_out[i].get(animal_type, 0) if animals_at_dest: while animals_at_dest: unload_count += 1 animals_at_dest &= animals_at_dest-1 unload_tracker[unload_count-1] = min(i+1, unload_tracker[unload_count-1]) # Load all the animals we can new_E = animal_types['E'] | zoos_in[i].get('E', 0) new_D = animal_types['D'] | zoos_in[i].get('D', 0) new_C = animal_types['C'] | zoos_in[i].get('C', 0) new_M = animal_types['M'] | zoos_in[i].get('M', 0) # Remove bad pairings state1 = State(i, unload_count, new_E, 0, new_C, 0) if state1 not in parent: parent[state1] = s dfs_visit(state1) state2 = State(i, unload_count, 0, new_D, 0, new_M) if state2 not in parent: parent[state2] = s dfs_visit(state2) dfs_visit(intial_state) return unload_tracker def str_and_replace(x): if x == float('inf'): return '-1' return str(x) if __name__ == "__main__": cases = int(input().strip()) for a0 in range(cases): m, n = input().strip().split(' ') m, n = [int(m), int(n)] t = input().strip().split(' ') s = list(map(int, input().strip().split(' '))) d = list(map(int, input().strip().split(' '))) result = minimumZooNumbers(m, n, t, s, d) print (" ".join(map(str_and_replace, result)))