#!/bin/python3 import sys import itertools def identify_segments(m, n, t, s, d): zoo_bitmap = [[[], 0,0] for _ in range(m+1)] # 3 cells per zoo: end_here_registry, crosses, starts_here for animal in range(n): s_i, d_i = s[animal], d[animal] zoo_bitmap[s_i][2] |= 1 # starts_here for i in range(s_i+1, d_i): zoo_bitmap[i][1] |= 1 # crosses; n.b. crosses is set iff we are IN a segment zoo_bitmap[d_i][0].append(animal) segments = [] in_seg = False seg_start = 0 seg_registry = [] for i in range(1, m+1): e_reg, c, s = zoo_bitmap[i] if e_reg: seg_registry.extend(e_reg) if in_seg: if c: continue # else we are at the end of a segment in_seg = False segments.append(((seg_start, i), seg_registry)) if s: seg_start = i in_seg = True seg_registry = [] else: # not in seg if s: seg_start = i in_seg = True seg_registry = [] return segments def are_good_together(a, b, t): if t[a] == 'E' or t[a] == 'C': return t[b] == 'E' or t[b] == 'C' if t[a] == 'D' or t[a] == 'M': return t[b] == 'D' or t[b] == 'M' return False def are_overlapping(a, b, s, d): return not (d[a] <= s[b] or d[b] <= s[a]) def is_feasible(combo, t, s, d): for a, b in itertools.combinations(combo, 2): if not are_good_together(a, b, t) and are_overlapping(a, b, s, d): return False return True def analyze_segment(m, n, t, s, d, seg, animals_in_seg): analysis = [] # a_i contains the minimum zoo number to deliver i+1 animals in the segment for i in range(n): # need to find the "nearest-ending zoo" combo of i+1 animals for combo in itertools.combinations(animals_in_seg, i+1): if is_feasible(combo, t, s, d): analysis.append(d[combo[-1]]) # by construction the last animal in the combo # is the farthest along the zoo line break if i >= len(analysis): # a combo was not found break # this and all following i will be -1 return analysis def combine_segment_analyses(n, segment_analysis): result = [] for analysis in segment_analysis: result.extend(analysis) result.extend([-1] * (n-len(result))) return result def minimumZooNumbers(m, n, t, s, d): # Return a list of length n consisting of the answers segments = identify_segments(m, n, t, s, d) segment_analysis = [] for seg, animals_in_seg in segments: segment_analysis.append(analyze_segment(m, n, t, s, d, seg, animals_in_seg)) result = combine_segment_analyses(n, segment_analysis) return result 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, result)))