import sys def solve(): input_data = sys.stdin.read().split() if not input_data: return it = iter(input_data) num_test_cases = int(next(it)) output = [] for _ in range(num_test_cases): building_floors = int(next(it)) num_elevators = int(next(it)) start_floors = [int(next(it)) for _ in range(num_elevators)] goal_floors = [int(next(it)) for _ in range(num_elevators)] # 各エレベーターの (初期位置, 目的位置) をソート elevators = sorted(zip(start_floors, goal_floors)) possible = True for i in range(num_elevators - 1): s1, g1 = elevators[i] s2, g2 = elevators[i + 1] # 順序が逆転している場合は到達不可能 if g1 > g2: possible = False break # 同じ階に到達する場合、最初からその階に揃っていなければ合流不可能 if g1 == g2: if not (s1 == g1 and s2 == g2): possible = False break if not possible: output.append("-1") continue total_operations = 0 for i in range(num_elevators): curr_s, curr_g = elevators[i] if curr_s == curr_g: continue if curr_s < curr_g: # 右へ移動 if i == num_elevators - 1: total_operations += 1 else: next_s, next_g = elevators[i + 1] right_bound = max(next_s, next_g) d0 = right_bound - curr_s d_target = right_bound - curr_g k = 1 val = d_target * 2 while val < d0: val *= 2 k += 1 total_operations += k else: # 左へ移動 if i == 0: total_operations += 1 else: prev_s, prev_g = elevators[i - 1] left_bound = min(prev_s, prev_g) d0 = curr_s - left_bound d_target = curr_g - left_bound k = 1 val = d_target * 2 while val < d0: val *= 2 k += 1 total_operations += k output.append(str(total_operations)) sys.stdout.write("\n".join(output) + "\n") if __name__ == "__main__": solve()