Read problem statements in [Vietnamese],
[Bengali], [Mandarin Chinese], and [Russian] as well. 

There are $N$ cities in Chefland numbered from $1$ to $N$ and every city has a railway station. Some cities have a train and each city has at most one train originating from it. The trains are represented by an array $A$, where $A_{i} = 0$ means the $i$-th city doesn't have any train originating from it, $A_{i} = 1$ means the train originating from the $i$-th city is moving right (to a higher numbered city), and $A_{i} = 2$ means the train originating from the $i$-th city is moving left (to a lower numbered city).

Each train keeps on going forever in its direction and takes $1$ minute to travel from the current station to the next one. There is a special station at city $1$ which lets travellers instantaneously teleport to any other station that currently has a train. Teleportation and getting on a train once in the city both take $0$ minutes and all trains start at time $0$.

There are $M$ travellers at city $1$, and the $i$-th traveller has destination city $B_{i}$. They ask Chef to guide them to teleport to a particular station from which they can catch a train to go to their destination in the least time possible. In case it's not possible for a person to reach his destination, print $-1$.

Note: The input and output of this problem are large, so prefer using fast input/output methods.

------ Input ------

The first line contains an integer $T$, the number of test cases. Then the test cases follow. 
Each test case contains three lines of input.
The first line contains two integers $N$, $M$.
The second line contains $N$ integers $A_{1}, A_{2}, \ldots, A_{N}$.
The third line contains $M$ integers $B_{1}, B_{2}, \ldots, B_{M}$.

------ Output ------
For each test case, output $M$ space-separated integers $C_{1}, C_{2}, \ldots, C_{M}$, where $C_{i}$ is the minimum time required by the $i$-th traveller to reach his destination and if the $i$-th traveller can't reach his destination, $C_{i} = -1$.

------ Constraints  ------
$1 ≤ N, M ≤ 10^{5}$
$0 ≤ A_{i} ≤ 2$
$1 ≤ B_{i} ≤ N$
The sum of $N$ over all test cases is at most $10^{6}$.
The sum of $M$ over all test cases is at most $10^{6}$.

------ Subtasks ------
Subtask #1 (100 points): original constraints

----- Sample Input 1 ------ 
3

5 1

1 0 0 0 0

5

5 1

1 0 0 0 2

4

5 2

2 0 0 0 1

3 1
----- Sample Output 1 ------ 
4

1

-1 0
----- explanation 1 ------ 
Test Case $1$: The only person takes the train from station $1$ and hence takes $|5 - 1| = 4$ minutes to reach his destination.

Test Case $2$: The only person takes the train from station $5$ and hence takes $|5 - 4| = 1$ minute to reach his destination.

Test Case $3$: Since no train passes station $3$, it's impossible for the first person to reach his destination and since the second person is already at station $1$, it takes him $0$ minutes to reach his destination.

Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Sorting

Complete search
Skill types: Dynamic programming

Sorting

Complete search

Starter code:

Solutions:
import sys
from os import path
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	ar = a[::-1]
	b = list(map(int, input().split()))
	larr = [0]
	rarr = []
	nrstl = 0 if a[0] == 1 else -1
	nrstr = -1
	for i in range(1, n):
		if a[i] > 0:
			larr.append(0)
			if a[i] == 1:
				nrstl = i
		else:
			larr.append(i - nrstl if nrstl != -1 else -1)
	for i in range(n - 1):
		if ar[i] > 0:
			rarr.append(0)
			if ar[i] == 2:
				nrstr = i
		else:
			rarr.append(i - nrstr if nrstr != -1 else -1)
	rarr.append(0)
	rarr = rarr[::-1]
	for i in range(m):
		st = b[i] - 1
		if larr[st] > -1 and rarr[st] > -1:
			print(min(rarr[st], larr[st]), end=' ')
		elif larr[st] != rarr[st]:
			print(max(larr[st], rarr[st]), end=' ')
		else:
			print(-1, end=' ')
	print()


try:
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		llst = []
		rlst = []
		maxl = -1
		maxr = -1
		for i in range(n):
			if a[i] == 1:
				llst.append(i)
				maxl = i
			else:
				llst.append(maxl)
		for i in range(n - 1, -1, -1):
			if a[i] == 2:
				rlst.append(i)
				maxr = i
			else:
				rlst.append(maxr)
		rlst.reverse()
		flst = []
		for i in range(m):
			if a[b[i] - 1] != 0 or b[i] - 1 == 0:
				flst.append(0)
			elif llst[b[i] - 1] == -1 and rlst[b[i] - 1] == -1:
				flst.append(-1)
			elif llst[b[i] - 1] == -1:
				flst.append(rlst[b[i] - 1] - (b[i] - 1))
			elif rlst[b[i] - 1] == -1:
				flst.append(b[i] - 1 - llst[b[i] - 1])
			else:
				x = min(b[i] - 1 - llst[b[i] - 1], rlst[b[i] - 1] - (b[i] - 1))
				flst.append(x)
		print(*flst, sep=' ')
except:
	pass


ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
from collections import defaultdict
import sys
sys.setrecursionlimit(100000)
t = ri()
for test in range(t):
	(n, m) = rl()
	l = rl()
	d = rl()
	train = [float('inf')] * n
	s = float('-inf')
	for i in range(n):
		if i == 0:
			train[i] = 0
		elif l[i] != 0:
			train[i] = 0
		else:
			train[i] = i - s
		if l[i] == 1:
			s = i
	s = float('inf')
	for i in range(n - 1, -1, -1):
		train[i] = min(train[i], s - i)
		if l[i] == 2:
			s = i
	ans = []
	for i in d:
		if train[i - 1] == float('inf'):
			ans.append(-1)
		else:
			ans.append(train[i - 1])
	for i in range(len(ans) - 1):
		print(ans[i], end=' ')
	print(ans[-1])


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = [n * 2] * n
	r = [n * 2] * n
	l[0] = 0
	st = False
	for i in range(n):
		if a[i] == 1:
			l[i] = 0
			st = True
		elif st:
			l[i] = l[i - 1] + 1
	en = False
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			r[i] = 0
			en = True
		elif en:
			r[i] = r[i + 1] + 1
	c = [-1] * n
	for i in range(n):
		c[i] = min(l[i], r[i])
		if c[i] > n:
			c[i] = -1
	for i in b:
		print(c[i - 1] if i != 0 else 0, end=' ')
	print()


import sys, math
from collections import Counter
sys.setrecursionlimit(10 ** 5)

def pro(arr, q):
	n = len(arr)
	left = [math.inf] * n
	right = [math.inf] * n
	left[0] = 0
	f = 0
	for i in range(n):
		if arr[i] == 1:
			left[i] = 0
			f = 1
			continue
		if f:
			left[i] = left[i - 1] + 1
	f = 0
	for i in range(n - 1, -1, -1):
		if arr[i] == 2:
			right[i] = 0
			f = 1
			continue
		if f:
			right[i] = right[i + 1] + 1
	for i in q:
		ans = min(left[i - 1], right[i - 1])
		print(-1 if ans == math.inf else ans, end=' ')
	print()
n = int(input())
for i in range(n):
	(p, q) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	c = list(map(int, input().split()))
	pro(arr, c)


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	trains = list(map(int, input().split()))
	dest = list(map(int, input().split()))
	lmin = [1000001 for _ in range(n)]
	rmin = [1000001 for _ in range(n)]
	c = 1
	flag = False
	for i in range(n):
		if trains[i] == 1:
			lmin[i] = 0
			c = 1
			flag = True
		elif flag:
			lmin[i] = c
			c += 1
	c = 1
	flag = False
	for i in range(n - 1, -1, -1):
		if trains[i] == 2:
			rmin[i] = 0
			c = 1
			flag = True
		elif flag:
			rmin[i] = c
			c += 1
	r = []
	for ele in dest:
		if ele == 1:
			r.append(0)
		else:
			res = min(lmin[ele - 1], rmin[ele - 1])
			r.append(res if res != 1000001 else -1)
	print(*r)


NONE = 0
RIGHT = 1
LEFT = 2

def SHROUTE(N, M, As, Bs):
	closest_left = []
	closest_right = []
	for (i, direction) in enumerate(As, start=1):
		if direction == RIGHT:
			closest_left.append(i)
		elif closest_left:
			closest_left.append(closest_left[-1])
		else:
			closest_left.append(-1)
	for (i, direction) in list(enumerate(As, start=1))[::-1]:
		if direction == LEFT:
			closest_right.append(i)
		elif closest_right:
			closest_right.append(closest_right[-1])
		else:
			closest_right.append(-1)
	closest_right = closest_right[::-1]
	result = []
	for b in Bs:
		if b == 1:
			result.append(0)
			continue
		left = closest_left[b - 1]
		right = closest_right[b - 1]
		dists = []
		if left != -1:
			dists.append(abs(b - left))
		if right != -1:
			dists.append(abs(b - right))
		result.append(min(dists, default=-1))
	print(' '.join((str(x) for x in result)))
for _ in range(int(input())):
	(N, M) = (int(x) for x in input().split())
	As = [int(x) for x in input().split()]
	Bs = [int(x) for x in input().split()]
	SHROUTE(N=N, M=M, As=As, Bs=Bs)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	(l3, l4) = ([-1] * (n + 1), [-1] * (n + 1))
	(m1, m2) = (-1, -1)
	for i in range(n):
		if l1[i] == 1:
			m1 = i + 1
		if l1[n - 1 - i] == 2:
			m2 = n - i
		l3[i + 1] = m1
		l4[n - i] = m2
	for i in l2:
		if i == 1:
			print(0, end=' ')
		elif l3[i] > 0 and l4[i] > 0:
			print(min(i - l3[i], l4[i] - i), end=' ')
		elif l3[i] > 0:
			print(i - l3[i], end=' ')
		elif l4[i] > 0:
			print(l4[i] - i, end=' ')
		else:
			print(-1, end=' ')
	print()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	station = list(map(int, input().split()))
	dest = list(map(int, input().split()))
	dis1 = [-1] * n
	dis2 = [-1] * n
	(right, left) = (-1, -1)
	for i in range(n):
		if station[i] == 1:
			dis1[i] = i
			right = i
		else:
			dis1[i] = right
	for i in range(n - 1, -1, -1):
		if station[i] == 2:
			dis2[i] = i
			left = i
		else:
			dis2[i] = left
	res = []
	for i in range(m):
		d = dest[i]
		if d == 1:
			res.append(0)
			continue
		if dis1[d - 1] == -1 and dis2[d - 1] == -1:
			res.append(-1)
			continue
		if dis1[d - 1] == -1 and dis2[d - 1] != -1:
			res.append(abs(dis2[d - 1] - (d - 1)))
			continue
		if dis1[d - 1] != -1 and dis2[d - 1] == -1:
			res.append(abs(dis1[d - 1] - (d - 1)))
			continue
		res.append(min(abs(dis2[d - 1] - (d - 1)), abs(dis1[d - 1] - (d - 1))))
	print(*res)


t = int(input())
for k in range(t):
	(n, m) = input().split()
	(n, m) = (int(n), int(m))
	s = input().split()
	for i in range(n):
		s[i] = int(s[i])
	_b = input().split()
	for i in range(m):
		_b[i] = int(_b[i])
	prep1 = [-1] * n
	prep2 = [-1] * n
	pr1 = -1
	pr2 = -1
	for i in range(n):
		if s[i] == 1:
			prep1[i] = i
			pr1 = i
		else:
			prep1[i] = pr1
	for i in range(n - 1, -1, -1):
		if s[i] == 2:
			prep2[i] = i
			pr2 = i
		else:
			prep2[i] = pr2
	ans = ''
	for i in range(m):
		b = _b[i]
		if b == 1:
			ans += '0 '
			continue
		if prep1[b - 1] == -1 and prep2[b - 1] == -1:
			ans += '-1 '
			continue
		if prep1[b - 1] == -1 and prep2[b - 1] != -1:
			ans += str(abs(prep2[b - 1] - (b - 1))) + ' '
			continue
		if prep1[b - 1] != -1 and prep2[b - 1] == -1:
			ans += str(abs(prep1[b - 1] - (b - 1))) + ' '
			continue
		ans += str(min(abs(prep2[b - 1] - (b - 1)), abs(prep1[b - 1] - (b - 1)))) + ' '
	print(ans[:len(ans) - 1])


from math import inf
import sys
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = list(map(int, sys.stdin.readline().split()))
	arr = list(map(int, sys.stdin.readline().split()))
	q = list(map(int, sys.stdin.readline().split()))
	left = [inf] * n
	right = [inf] * n
	left[0] = 0 if arr[0] == 1 else inf
	for i in range(1, n):
		if arr[i] == 1:
			left[i] = 0
		else:
			left[i] = left[i - 1] + 1
	right[n - 1] = 0 if arr[n - 1] == 2 else inf
	for i in range(n - 2, -1, -1):
		if arr[i] == 2:
			right[i] = 0
		else:
			right[i] = right[i + 1] + 1
	for i in q:
		if i == 1:
			print(0, end=' ')
		else:
			val = min(left[i - 1], right[i - 1])
			print(-1 if val == inf else val, end=' ')
	print()


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	lst = list(map(int, input().split()))
	query = list(map(int, input().split()))
	lst1 = [float('inf')] * n
	left = -1
	for i in range(n):
		if lst[i] == 1:
			lst1[i] = 0
			left = i
		elif left != -1:
			lst1[i] = i - left
	lst1[0] = 0
	right = -1
	lst2 = [float('inf')] * n
	for i in range(n - 1, -1, -1):
		if lst[i] == 2:
			right = i
			lst2[i] = 0
		elif right != -1:
			lst2[i] = right - i
	for i in range(m):
		x = min(lst1[query[i] - 1], lst2[query[i] - 1])
		if x != float('inf'):
			print(x, end=' ')
		else:
			print(-1, end=' ')
	print()


T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	L = list(map(int, input().split()))
	M = [10 ** 6 for i in range(n)]
	M[0] = 0
	if 1 in L:
		i = L.index(1)
		x = i
		y = x
		for i in range(y, n):
			if L[i] == 1:
				M[i] = 0
				x = i
			else:
				M[i] = i - x
	if 2 in L:
		S = L.copy()
		S.reverse()
		j = S.index(2)
		x = n - j - 1
		y = x
		for i in range(y, -1, -1):
			if L[i] == 2:
				M[i] = 0
				x = i
			else:
				M[i] = min(M[i], x - i)
	N = list(map(int, input().split()))
	K = [0 for i in range(m)]
	for i in range(m):
		a = N[i]
		if M[a - 1] == 10 ** 6:
			K[i] = -1
		else:
			K[i] = M[a - 1]
	print(*K)


import sys
MAX = 10000000

def construct_left(a0, n0):
	lt = [MAX] * n0
	if a0[0] == 2:
		lt[0] = 0
	if a0[n0 - 1] == 2:
		lt[n0 - 1] = 0
	for i in reversed(range(0, n0 - 1)):
		if a0[i] == 2:
			lt[i] = 0
		else:
			lt[i] = min(lt[i], lt[i + 1] + 1)
	return lt

def construct_right(a0, n0):
	r = [MAX] * n0
	if a0[0] == 1:
		r[0] = 0
	for i in range(1, n):
		if a0[i] == 1:
			r[i] = 0
		else:
			r[i] = min(r[i], r[i - 1] + 1)
	return r
t = int(sys.stdin.readline())
for _ in range(t):
	[n, m] = list(map(int, sys.stdin.readline().split()))
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	left = construct_left(a, n)
	right = construct_right(a, n)
	result = [MAX] * n
	for i in range(n):
		result[i] = 0 if a[i] != 0 else min(left[i], right[i])
	for i in range(m):
		bi = b[i]
		if bi == 1:
			print(0, end=' ')
			continue
		if result[bi - 1] == MAX:
			print(-1, end='' if i == m - 1 else ' ')
		else:
			print(result[bi - 1], end='' if i == m - 1 else ' ')
	print('')


strng = lambda : input()
inp = lambda : int(input())
mul = lambda : map(int, input().split())
jn = lambda x, l: x.join(map(str, l))
strlst = lambda : list(input())
lst = lambda : list(map(int, input().split()))
dd = lambda : defaultdict(lambda : 0)
from collections import defaultdict
import sys
from math import ceil, log, floor, sqrt, gcd, log10
for _ in range(inp()):
	(n, k) = mul()
	a = lst()
	b = lst()
	l = []
	cnt = sys.maxsize
	for i in range(n):
		if a[i] == 1:
			cnt = 0
		l += [cnt]
		if cnt != sys.maxsize:
			cnt += 1
	cnt = sys.maxsize
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			cnt = 0
		l[i] = min(l[i], cnt)
		if cnt != sys.maxsize:
			cnt += 1
	for i in range(k):
		if b[i] == 1:
			print(0, end=' ')
			continue
		if l[b[i] - 1] == sys.maxsize:
			print(-1, end=' ')
			continue
		print(l[b[i] - 1], end=' ')
	print()


from math import inf
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = [int(x) for x in input().split()]
	q = [int(x) for x in input().split()]
	left = [inf] * n
	right = [inf] * n
	left[0] = 0 if arr[0] == 1 else inf
	for i in range(1, n):
		if arr[i] == 1:
			left[i] = 0
		else:
			left[i] = left[i - 1] + 1
	right[n - 1] = 0 if arr[n - 1] == 2 else inf
	for i in range(n - 2, -1, -1):
		if arr[i] == 2:
			right[i] = 0
		else:
			right[i] = right[i + 1] + 1
	for i in q:
		if i == 1:
			print(0, end=' ')
		else:
			val = min(left[i - 1], right[i - 1])
			print(-1 if val == inf else val, end=' ')
	print()


def cal(n, m, c, p):
	l = [-1] * (n + 1)
	a = [0]
	b = []
	count = 0
	f = 0
	for i in c:
		if (i == 0 or i == 2) and f == 0:
			a.append(-1)
		elif i == 1:
			a.append(0)
			count = 0
			f = 1
		else:
			count += 1
			a.append(count)
	count = 0
	f = 0
	c.reverse()
	for i in c:
		if (i == 0 or i == 1) and f == 0:
			b.append(-1)
		elif i == 2:
			b.append(0)
			count = 0
			f = 1
		else:
			count += 1
			b.append(count)
	b.reverse()
	b.insert(0, 0)
	a[1] = 0
	b[1] = 0
	for i in p:
		if min(a[i], b[i]) != -1:
			d = min(a[i], b[i])
		else:
			d = max(a[i], b[i])
		print(d, end=' ')
T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	city = list(map(int, input().split()))
	person = list(map(int, input().split()))
	cal(N, M, city, person)
	print()


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	l = []
	c = -1
	for j in range(n):
		if x[j] == 1:
			c = j
		l.append(c)
	r = [-1 for i in range(n)]
	c = -1
	for k in range(n - 1, -1, -1):
		if x[k] == 2:
			c = k
		r[k] = c
	for z in y:
		z -= 1
		a = l[z]
		b = r[z]
		if z == 0:
			print(0, end=' ')
		elif a == -1 and b == -1:
			print(-1, end=' ')
		elif a == -1:
			print(b - z, end=' ')
		elif b == -1:
			print(z - a, end=' ')
		else:
			print(min(b - z, z - a), end=' ')
	print()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	st = list(map(int, input().split()))
	ps = list(map(int, input().split()))
	l = []
	ind = -1
	for i in range(n):
		if st[i] == 1:
			ind = i
		l.append(ind)
	r = [-1 for i in range(n)]
	ind = -1
	for i in range(n - 1, -1, -1):
		if st[i] == 2:
			ind = i
		r[i] = ind
	for ele in ps:
		ele = ele - 1
		a = l[ele]
		b = r[ele]
		if ele == 0:
			print(0, end=' ')
		elif a == -1 and b == -1:
			print(-1, end=' ')
		elif a == -1:
			print(b - ele, end=' ')
		elif b == -1:
			print(ele - a, end=' ')
		else:
			print(min(b - ele, ele - a), end=' ')
	print()


import sys
maxi = sys.maxsize
T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	station = list(map(int, input().split()))
	city = list(map(int, input().split()))
	diss1 = [maxi] * N
	diss2 = [maxi] * N
	if station[0] == 1:
		diss1[0] = 0
	for i in range(1, N):
		if station[i] == 2:
			if diss1[i - 1] != maxi:
				diss1[i] = diss1[i - 1] + 1
		if station[i] == 0:
			if diss1[i - 1] != maxi:
				diss1[i] = diss1[i - 1] + 1
		if station[i] == 1:
			diss1[i] = 0
	if station[N - 1] == 2:
		diss2[N - 1] = 0
	for i in range(N - 2, -1, -1):
		if station[i] == 1:
			if diss2[i + 1] != maxi:
				diss2[i] = 1 + diss2[i + 1]
		if station[i] == 0:
			if diss2[i + 1] != maxi:
				diss2[i] = 1 + diss2[i + 1]
		if station[i] == 2:
			diss2[i] = 0
	for i in city:
		if i == 1:
			print(0, end=' ')
			continue
		if station[i - 1] != 0:
			print(0, end=' ')
		elif diss1[i - 1] == maxi and diss2[i - 1] == maxi:
			print(-1, end=' ')
		else:
			print(min(diss2[i - 1], diss1[i - 1]), end=' ')
	print()


import bisect
n_testcase = int(input())
for testcase in range(n_testcase):
	(n, m) = (int(x) for x in input().split())
	facings = [int(x) for x in input().split()]
	destinations = [int(x) for x in input().split()]
	leftward_stations = []
	rightward_stations = []
	for (i, facing) in enumerate(facings, start=1):
		if facing == 1:
			rightward_stations.append(i)
		if facing == 2:
			leftward_stations.append(i)
	for destination in destinations:
		if destination == 1:
			print(0, end=' ')
			continue
		min_time = n + 1
		if leftward_stations and destination <= leftward_stations[-1]:
			i = bisect.bisect_left(leftward_stations, destination)
			station = leftward_stations[i]
			min_time = min(min_time, station - destination)
		if rightward_stations and destination >= rightward_stations[0]:
			i = bisect.bisect_right(rightward_stations, destination) - 1
			station = rightward_stations[i]
			min_time = min(min_time, destination - station)
		print(min_time if min_time < n + 1 else -1, end=' ')
	print()


import sys

def inp():
	return sys.stdin.readline()

def out(var):
	sys.stdout.write(str(var) + '\n')

def I():
	return inp()

def II():
	return int(inp())

def FI():
	return float(inp())

def SI():
	return list(str(inp()))

def MI():
	return map(int, inp().split())

def LI():
	return list(MI())

def SLI():
	return sorted(LI())

def MF():
	return map(float, inp().split())

def LF():
	return list(MF())

def SLF():
	return sorted(LF())
sys.setrecursionlimit(10 ** 9)
for t in range(II()):
	(n, m) = MI()
	ans = []
	list1 = LI()[:n]
	list2 = LI()[:m]
	start = list1[0]
	prefix2 = [-1] * (n + 1)
	prefix1 = [-1] * (n + 1)
	for i in range(n - 1, 0, -1):
		if list1[i] == 2:
			prefix2[i] = i
			continue
		prefix2[i] = prefix2[i + 1]
	if list1[0] == 2:
		prefix2[0] = 0
	else:
		prefix2[0] = prefix2[1]
	if list1[0] == 1:
		prefix1[0] = 0
	for i in range(1, n):
		if list1[i] == 1:
			prefix1[i] = i
			continue
		prefix1[i] = prefix1[i - 1]
	for i in range(m):
		val1 = 2 ** 31
		val2 = 2 ** 31
		ind = list2[i] - 1
		if ind == 0:
			print(0, end=' ')
		elif list1[ind] != 0:
			print(0, end=' ')
		else:
			if ind >= prefix1[ind] and prefix1[ind] != -1:
				val1 = abs(ind - prefix1[ind])
			if ind <= prefix2[ind] and prefix2[ind] != -1:
				val2 = abs(ind - prefix2[ind])
			ans = min(val1, val2)
			if ans == 2 ** 31:
				print(-1, end=' ')
			else:
				print(ans, end=' ')
	print()


n = int(input())
while n > 0:
	input()
	t = input().strip().split(' ')
	p = input().strip().split(' ')
	(latest_left, latest_right) = (-1, -1)
	(left_shortest, right_shortest) = ([0] * len(t), [0] * len(t))
	for i in range(len(t)):
		if latest_right != -1:
			right_shortest[i] = i - latest_right
		if t[i] == '1':
			latest_right = i
	for i in range(len(t) - 1, -1, -1):
		if latest_left != -1:
			left_shortest[i] = latest_left - i
		if t[i] == '2':
			latest_left = i
	res = []
	for p1 in p:
		dest = int(p1)
		if dest == 1:
			res.append('0')
			continue
		if t[dest - 1] == '1' or t[dest - 1] == '2':
			res.append('0')
			continue
		min_dist = min(left_shortest[dest - 1], right_shortest[dest - 1])
		if min_dist == 0:
			if left_shortest[dest - 1] != 0:
				res.append(str(left_shortest[dest - 1]))
			elif right_shortest[dest - 1] != 0:
				res.append(str(right_shortest[dest - 1]))
			else:
				res.append('-1')
		else:
			res.append(str(min_dist))
	print(' '.join(res))
	n -= 1


from bisect import bisect, bisect_left
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	(left, right) = ([], [])
	for i in range(n):
		if A[i] == 1:
			right.append(i)
		elif A[i] == 2:
			left.append(i)
	for b in B:
		b -= 1
		if b == 0:
			print('0', end=' ')
		else:
			k = bisect_left(left, b)
			l = bisect(right, b)
			res = -1
			if k != len(left):
				res = left[k] - b
			if l != 0:
				if res != -1:
					res = min(b - right[l - 1], res)
				else:
					res = b - right[l - 1]
			print(res, end=' ')
	print()


from bisect import bisect_left as bl, bisect_right as br
inp = lambda x: map(int, x.split())
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(inp(input()))
	b = list(inp(input()))
	d = {}
	(tl, tr) = (set(), set())
	for i in range(max(m, n)):
		if i < m:
			try:
				d[b[i]].append(i)
			except:
				d[b[i]] = [i]
		if i < n and a[i] != 0:
			if a[i] == 1:
				tr.add(i + 1)
			else:
				tl.add(i + 1)
	flags = ['-1'] * m
	(tl, tr) = (list(tl), list(tr))
	(l, r) = (len(tl), len(tr))
	for k in d:
		if k == 1:
			for j in d[k]:
				flags[j] = '0'
		else:
			ind_l = bl(tl, k)
			ind_r = br(tr, k)
			(p1, p2) = (n, n)
			if ind_l != l:
				p1 = abs(k - tl[ind_l])
			if ind_r != 0:
				p2 = abs(k - tr[ind_r - 1])
			v = str(min(p1, p2))
			if v == str(n):
				v = '-1'
			for j in d[k]:
				flags[j] = v
	print(' '.join(flags))


T = int(input())
for t in range(T):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	(R, L) = ([N] * N, [N] * N)
	for i in range(N):
		if A[i] == 1:
			R[i] = 0
		elif i > 0:
			R[i] = R[i - 1] + 1
		if A[N - i - 1] == 2:
			L[N - i - 1] = 0
		elif i > 0:
			L[N - i - 1] = L[N - i] + 1
	res = [-1] * M
	for i in range(M):
		if B[i] == 1:
			res[i] = 0
			continue
		res[i] = min(L[B[i] - 1], R[B[i] - 1])
		if res[i] >= N:
			res[i] = -1
	print(*res)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	max = 10 ** 9
	test = [None] * n
	test[0] = 0
	for i in range(1, n):
		if a[i] != 0:
			test[i] = 0
		else:
			test[i] = max
	r = -1
	for i in range(n):
		if a[i] == 1:
			r = i
		elif r != -1:
			test[i] = min(test[i], i - r)
	l = -1
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			l = i
		elif l != -1:
			test[i] = min(test[i], l - i)
	for i in range(m):
		des = b[i] - 1
		if test[des] == max:
			print(-1, end=' ')
		else:
			print(test[des], end=' ')
	print()


def func(A, N, mindr, mindl):
	timer = 0
	flagr = -1
	flagl = -1
	mindr[0] = 0
	mindl[0] = 0
	for m in range(0, N):
		if A[m] == 1:
			flagr = m
			break
	if flagr != -1:
		for i in range(flagr, N):
			if A[i] == 1:
				timer = 0
			else:
				timer += 1
			mindr[i] = timer
	timer = 0
	for n in range(N - 1, -1, -1):
		if A[n] == 2:
			flagl = n
			break
	if flagl != -1:
		for j in range(flagl, -1, -1):
			if A[j] == 2:
				timer = 0
			else:
				timer += 1
			mindl[j] = timer
for t in range(int(input())):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	mindr = [1000001 for _ in range(N)]
	mindl = [1000001 for _ in range(N)]
	func(A, N, mindr, mindl)
	ans = []
	for k in range(M):
		x = B[k] - 1
		if min(mindr[x], mindl[x]) == 1000001:
			ans.append(-1)
		else:
			ans.append(min(mindr[x], mindl[x]))
	print(*ans)


def shortestRoute(N, M, A, B):
	moving_right = [float('inf')] * (N + 1)
	for i in range(1, N + 1):
		if A[i - 1] == 1:
			moving_right[i] = 0
		else:
			moving_right[i] = min(moving_right[i], moving_right[i - 1] + 1)
	moving_left = [float('inf')] * (N + 1)
	for i in range(N, 0, -1):
		if A[i - 1] == 2:
			moving_left[i] = 0
		elif i != N:
			moving_left[i] = min(moving_left[i], moving_left[i + 1] + 1)
	moving_left[1] = 0
	moving_right[1] = 0
	distance = [float('inf')] * (N + 1)
	for i in range(N + 1):
		distance[i] = min(moving_left[i], moving_right[i])
		if distance[i] == float('inf'):
			distance[i] = -1
	L = []
	for i in B:
		L.append(distance[i])
	return L
T = int(input())
for case in range(T):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	for x in shortestRoute(N, M, A, B):
		print(x, end=' ')
	print('')


marker = 1000000000

def solve():
	(N, M) = [int(x) for x in str(input()).split(' ')]
	A = [0]
	A.extend([int(x) for x in str(input()).split(' ')])
	B = [int(x) for x in str(input()).split(' ')]
	C = [marker] * (N + 1)
	has_train = False
	train_pos = -1
	for i in range(1, len(A)):
		if A[i] == 1:
			has_train = True
			train_pos = i
			C[i] = 0
		elif has_train:
			C[i] = i - train_pos
			i += 1
	has_train = False
	train_pos = -1
	for i in range(len(A) - 1, 0, -1):
		if A[i] == 2:
			has_train = True
			train_pos = i
			C[i] = 0
		elif has_train:
			C[i] = min(C[i], train_pos - i)
			i += 1
	C[1] = 0
	result = ''
	for i in range(len(B)):
		if i > 0:
			result += ' '
		destination = B[i]
		if C[destination] == marker:
			result += '-1'
		else:
			result += str(C[destination])
	print(result)
T = int(input())
while T:
	solve()
	T -= 1


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	r = [-1] * n
	l = [-1] * n
	ctr = 0
	flag = False
	for i in range(n):
		if a[i] == 1:
			ctr = 0
			r[i] = ctr
			flag = True
		elif flag == True:
			ctr += 1
			r[i] = ctr
	ctr = 0
	flag = False
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			ctr = 0
			l[i] = ctr
			flag = True
		elif flag == True:
			ctr += 1
			l[i] = ctr
	res = []
	for i in range(m):
		if b[i] - 1 == 0:
			x = 0
		elif l[b[i] - 1] != -1 and r[b[i] - 1] != -1:
			x = min(l[b[i] - 1], r[b[i] - 1])
		elif l[b[i] - 1] == -1 and r[b[i] - 1] != -1:
			x = r[b[i] - 1]
		elif l[b[i] - 1] != -1 and r[b[i] - 1] == -1:
			x = l[b[i] - 1]
		elif l[b[i] - 1] == -1 and r[b[i] - 1] == -1:
			x = -1
		res.append(x)
	print(*res)


import sys
t = int(input())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().strip().split())
	a = list(map(int, sys.stdin.readline().strip().split()))
	b = list(map(int, sys.stdin.readline().strip().split()))
	distance1 = [0] * n
	pos = -1
	for i in range(0, n):
		if a[i] == 1:
			distance1[i] = 0
			pos = i
		elif a[i] == 0:
			if pos != -1:
				distance1[i] = abs(i - pos)
			else:
				distance1[i] = -1
		else:
			distance1[i] = 0
	distance2 = [0] * n
	pos2 = 0
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			distance2[i] = 0
			pos2 = i
		elif a[i] == 1:
			distance2[i] = 0
		elif pos2 != 0:
			distance2[i] = abs(i - pos2)
		else:
			distance2[i] = -1
	distance = [0] * n
	for i in range(n):
		if distance1[i] == -1 or distance2[i] == -1:
			distance[i] = max(distance1[i], distance2[i])
		else:
			distance[i] = min(distance1[i], distance2[i])
	ans = []
	for i in range(0, m):
		if b[i] == 1:
			distance[b[i] - 1] = 0
		ans.append(str(distance[b[i] - 1]))
	print(' '.join(ans))


import sys
from os import path
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output1.txt', 'w')
from heapq import heappop, heappush, heapify
from math import ceil
maxi = 2 * pow(10, 9)
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	src = list(map(int, input().split()))
	dest = list(map(int, input().split()))
	d = {}
	for i in range(n):
		d[i] = 0
	for i in range(1, n):
		if src[i] == 0:
			d[i] = maxi
	end = -1 * maxi
	start = end
	for i in range(n):
		if src[i] == 1:
			end = i
		if end != start:
			if not src[i]:
				d[i] = min(d[i], i - end)
	end = -1 * maxi
	for i in range(n - 1, -1, -1):
		if src[i] == 2:
			start = i
		if start != end:
			if not src[i]:
				d[i] = min(d[i], start - i)
	for i in range(m):
		if d[dest[i] - 1] == maxi:
			print(-1, end=' ')
		else:
			print(d[dest[i] - 1], end=' ')
	print()


import sys
from sys import stdin, stdout

def strictlyGreater(array, number, start, end):
	ans = -1
	while start <= end:
		mid = (start + end) // 2
		if array[mid] == number:
			ans = mid
		if array[mid] < number:
			start = mid + 1
		else:
			ans = mid
			end = mid - 1
	return ans

def strictlyLess(array, number, start, end):
	ans = -1
	while start <= end:
		mid = (start + end) // 2
		if array[mid] == number:
			ans = mid
		if array[mid] > number:
			end = mid - 1
		else:
			ans = mid
			start = mid + 1
	return ans
t = int(stdin.readline())
for i in range(t):
	(n, m) = map(int, stdin.readline().split())
	trains = list(map(int, stdin.readline().split()))
	destinations = list(map(int, stdin.readline().split()))
	right = []
	left = []
	for j in range(n):
		if trains[j] == 1:
			right.append(j + 1)
		if trains[j] == 2:
			left.append(j + 1)
	for station in destinations:
		if station == 1:
			ans = 0
		else:
			if len(left) > 0 and station > left[len(left) - 1]:
				shortestFromLeft = -1
			else:
				shortestFromLeft = strictlyGreater(left, station, 0, len(left) - 1)
			if len(right) > 0 and station < right[0]:
				shortestFromRight = -1
			else:
				shortestFromRight = strictlyLess(right, station, 0, len(right) - 1)
			if shortestFromRight != -1:
				shortestFromRight = station - right[shortestFromRight]
			else:
				shortestFromRight = sys.maxsize
			if shortestFromLeft != -1:
				shortestFromLeft = left[shortestFromLeft] - station
			else:
				shortestFromLeft = sys.maxsize
			ans = min(shortestFromLeft, shortestFromRight)
			if ans == sys.maxsize:
				ans = -1
		print(ans, end=' ')
	print()


t = int(input())
for t in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	right = [-1] * n
	left = [-1] * n
	ans = [0] * n
	final = []
	cntl = 0
	cntr = 0
	for i in range(n):
		if a[i] == 1:
			left[i] = 0
			cntl = 1
		elif cntl >= 1:
			left[i] = cntl
			cntl += 1
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			right[i] = 0
			cntr = 1
		elif cntr >= 1:
			right[i] = cntr
			cntr += 1
	for i in range(1, n):
		ans[i] = min(left[i], right[i])
		if ans[i] == -1:
			ans[i] = max(left[i], right[i])
	for destination in b:
		final.append(ans[destination - 1])
	print(*final)


def BSCeil(ar, key):
	first = 0
	last = len(ar) - 1
	ans = -1
	while first <= last:
		mid = (first + last) // 2
		if ar[mid] >= key:
			ans = ar[mid]
			last = mid - 1
		else:
			first = mid + 1
	return ans

def BSFloor(ar, key):
	first = 0
	last = len(ar) - 1
	ans = -1
	while first <= last:
		mid = (first + last) // 2
		if ar[mid] <= key:
			ans = ar[mid]
			first = mid + 1
		else:
			last = mid - 1
	return ans
t = int(input())
for t_cases in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	idx1s = []
	idx2s = []
	for i in range(n):
		if A[i] == 1:
			idx1s.append(i)
		if A[i] == 2:
			idx2s.append(i)
	for i in B:
		if A[i - 1] != 0 or i == 1:
			print('0', end=' ')
			continue
		x = -1
		y = -1
		ans = []
		if len(idx1s) != 0:
			x = BSFloor(idx1s, i - 1)
			if x != -1:
				ans.append(abs(i - 1 - x))
		if len(idx2s) != 0:
			y = BSCeil(idx2s, i - 1)
			if y != -1:
				ans.append(abs(y - i + 1))
		if x != -1 or y != -1:
			print(min(ans), end=' ')
		else:
			print(-1, end=' ')
	print()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	mp = {}
	max = 10 ** 9
	for i in range(n):
		if i == 0:
			mp[i] = 0
		elif a[i] != 0:
			mp[i] = 0
		else:
			mp[i] = max
	right = -1
	for i in range(n):
		if a[i] == 1:
			right = i
		if right != -1:
			if a[i] == 0:
				mp[i] = min(mp[i], i - right)
	left = -1
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			left = i
		if left != -1:
			if a[i] == 0:
				mp[i] = min(mp[i], left - i)
	arr = []
	for i in range(m):
		j = b[i] - 1
		if mp[j] != max:
			arr.append(mp[j])
		else:
			arr.append(-1)
	print(*arr)


def main():
	L = 1000000009
	for _ in range(int(input())):
		(N, M) = map(int, input().split())
		A = list(map(int, input().split()))
		B = list(map(int, input().split()))
		solution = [L] * N
		for i in range(N):
			if i == 0:
				solution[i] = 0
			elif A[i] != 0:
				solution[i] = 0
			else:
				solution[i] = L
		right = -1
		for i in range(N):
			if A[i] == 1:
				right = i
			if right != -1 and A[i] == 0:
				solution[i] = min(i - right, solution[i])
		left = -1
		for i in range(N - 1, -1, -1):
			if A[i] == 2:
				left = i
			if left != -1 and A[i] == 0:
				solution[i] = min(left - i, solution[i])
		for i in range(M):
			j = B[i] - 1
			if solution[j] == L:
				print(-1, end=' ')
			else:
				print(solution[j], end=' ')
		print()
main()


import sys
from sys import stdin, stdout
t = int(stdin.readline())
for i in range(t):
	(n, m) = map(int, stdin.readline().split())
	trains = list(map(int, stdin.readline().split()))
	destinations = list(map(int, stdin.readline().split()))
	l2r = [-1 for i in range(n)]
	r2l = l2r[:]
	time = -1
	for i in range(n):
		if trains[i] == 1:
			time = 0
		l2r[i] = time
		if time != -1:
			time += 1
	time = -1
	for i in range(n - 1, -1, -1):
		if trains[i] == 2:
			time = 0
		r2l[i] = time
		if time != -1:
			time += 1
	shortestTimes = [-1 for i in range(n)]
	for i in range(n):
		minTime = min(l2r[i], r2l[i])
		maxTime = max(l2r[i], r2l[i])
		if minTime == -1:
			shortestTimes[i] = maxTime
		else:
			shortestTimes[i] = minTime
	shortestTimes[0] = 0
	for i in range(m):
		print(shortestTimes[destinations[i] - 1], end=' ')
	print()


import sys
from sys import stdin, stdout
t = int(stdin.readline())
for i in range(t):
	(n, m) = map(int, stdin.readline().split())
	trains = list(map(int, stdin.readline().split()))
	destinations = list(map(int, stdin.readline().split()))
	station = [(sys.maxsize, sys.maxsize) for x in range(n)]
	right = []
	left = []
	for j in range(n):
		if trains[j] == 1:
			right.append(j + 1)
		if trains[j] == 2:
			left.append(j + 1)
	r = 0
	while r < len(right):
		x = right[r]
		station[x - 1] = (0, 0)
		x += 1
		if r == len(right) - 1:
			value = n - right[r]
		else:
			value = right[r + 1] - right[r] - 1
		for r1 in range(value):
			(leftD, rightD) = station[x - 1]
			station[x - 1] = (leftD, x - right[r])
			x += 1
		r += 1
	l = 0
	while l < len(left):
		y = left[l]
		station[y - 1] = (0, 0)
		y -= 1
		if l == 0:
			value = left[l] - 1
		else:
			value = left[l] - left[l - 1] - 1
		for l1 in range(value):
			(leftD, rightD) = station[y - 1]
			station[y - 1] = (left[l] - y, rightD)
			y -= 1
		l += 1
	for d in destinations:
		(leftD, rightD) = station[d - 1]
		ans = min(leftD, rightD)
		if ans == sys.maxsize:
			ans = -1
		if d == 1:
			ans = 0
		print(ans, end=' ')
	print()


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	n += 1
	a = list(map(int, input().split()))
	a = [0] + a
	b = list(map(int, input().split()))
	longg = 10000000000
	d = [longg for i in range(n)]
	l = -1
	for i in range(n):
		if a[i] == 1:
			l = i
		if l != -1:
			d[i] = i - l
	l = -1
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			l = i
		if l != -1 and d[i] > l - i:
			d[i] = l - i
	for i in b:
		if i == 1:
			print(0)
		else:
			print(d[i] if d[i] != longg else -1, end=' ')
	print()


from bisect import bisect_left, bisect
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	pas = list(map(int, input().split()))
	left = []
	left.append(float('inf'))
	left.append(-float('inf'))
	right = []
	right.append(float('inf'))
	right.append(-float('inf'))
	for i in range(n):
		if arr[i] == 1:
			right.append(i + 1)
		elif arr[i] == 2:
			left.append(i + 1)
	right.sort()
	left.sort()
	ans = []
	for i in range(m):
		val = pas[i]
		r = bisect(right, val)
		l = bisect_left(left, val)
		if val == 1:
			ans.append(0)
		else:
			a = min(abs(right[r - 1] - val), abs(left[l] - val))
			if a == float('inf'):
				ans.append(-1)
			else:
				ans.append(a)
	print(*ans)


def binary_search(arr, value, side):
	if len(arr) == 0:
		return -1
	if side == 1:
		start = 0
		end = len(arr) - 1
		result = -1
		while start <= end:
			mid = start + (end - start) // 2
			if arr[mid] >= value:
				result = arr[mid]
				end = mid - 1
			else:
				start = mid + 1
		if result == -1:
			return -1
		else:
			return result - value
	else:
		start = 0
		end = len(arr) - 1
		result = -1
		while start <= end:
			mid = start + (end - start) // 2
			if arr[mid] <= value:
				result = arr[mid]
				start = mid + 1
			else:
				end = mid - 1
		if result == -1:
			return -1
		return value - result

def solve(n, m, s, p):
	left_going_trains = []
	right_going_trains = []
	for i in range(n):
		if s[i] == 1:
			right_going_trains.append(i + 1)
		elif s[i] == 2:
			left_going_trains.append(i + 1)
	for i in range(m):
		if p[i] == 1:
			p[i] = 0
		elif s[p[i] - 1]:
			p[i] = 0
		else:
			ans1 = binary_search(left_going_trains, p[i], 1)
			ans2 = binary_search(right_going_trains, p[i], 0)
			if ans1 == -1 and ans2 == -1:
				p[i] = -1
			elif ans1 == -1:
				p[i] = ans2
			elif ans2 == -1:
				p[i] = ans1
			else:
				p[i] = min(ans1, ans2)
vaibhav = input
for _ in range(int(vaibhav())):
	(n, m) = map(int, vaibhav().split())
	s = tuple(map(int, vaibhav().split()))
	p = list(map(int, vaibhav().split()))
	solve(n, m, s, p)
	print(*p)


t = int(input())
for i in range(t):
	(n, m) = [int(n) for n in input().split()]
	arr = [int(item) for item in input().split()]
	brr = [int(item) for item in input().split()]
	last = -1
	crr = [0] * n
	for i in range(n):
		if arr[i] == 1:
			last = i
		else:
			if last == -1:
				crr[i] = -1
			if last != -1:
				crr[i] = i - last
	last = -1
	drr = [0] * n
	for i in range(n - 1, -1, -1):
		if arr[i] == 2:
			last = i
		else:
			if last == -1:
				drr[i] = -1
			if last != -1:
				drr[i] = last - i
	for i in range(m):
		k = brr[i] - 1
		if k == 0:
			print(0, end=' ')
			continue
		if arr[k] != 0:
			print(0, end=' ')
		elif crr[k] >= 0 and drr[k] >= 0:
			print(min(crr[k], drr[k]), end=' ')
		else:
			print(max(crr[k], drr[k]), end=' ')
	print(' ')


__author__ = 'Ronald Kaiser'
__email__ = 'raios dot catodicos at gmail dot com'
from bisect import bisect_left
from sys import stdin, stdout
from math import inf
read_line = lambda : stdin.readline().strip()
output_line = lambda x: stdout.write(x)
read_numbers = lambda : list(map(int, read_line().split()))

def find_min_dist(A, ones, twos, ones_set, twos_set, v):
	if v == 0 or v in ones_set or v in twos_set:
		return 0
	left = bisect_left(ones, v - 1)
	if left == len(ones) or ones[left] >= v:
		left -= 1
	if left == -1 or A[ones[left]] != 1 or ones[left] >= v:
		left = inf
	else:
		left = ones[left]
	right = bisect_left(twos, v + 1)
	if right == len(twos):
		right = -1
	if right == -1 or A[twos[right]] != 2 or twos[right] <= v:
		right = inf
	else:
		right = twos[right]
	if left == right == inf:
		return -1
	return min(abs(v - left), abs(right - v))

def solve(A, B):
	ones = [i for (i, v) in enumerate(A) if v == 1]
	twos = [i for (i, v) in enumerate(A) if v == 2]
	ones_set = set(ones)
	twos_set = set(twos)
	params = [A, ones, twos, ones_set, twos_set]
	solution = [str(find_min_dist(*params, b - 1)) for b in B]
	return ' '.join(solution) + '\n'

def main():
	for _ in range(int(input())):
		(N, M) = read_numbers()
		A = read_numbers()[:N]
		B = read_numbers()[:M]
		answer = solve(A, B)
		output_line(answer)
main()


for iii in range(int(input())):
	(n, m) = map(int, input().split())
	q = list(map(int, input().split()))
	w = [999999 for i in range(n)]
	found = -1
	ind = 0
	for i in range(n):
		if q[i] == 1:
			ind = i
			found = 1
		if found == -1:
			continue
		w[i] = i - ind
	ind = 0
	found = -1
	for i in range(n - 1, -1, -1):
		if q[i] == 2:
			ind = i
			found = 1
		if found == -1:
			continue
		w[i] = min(w[i], ind - i)
	e = []
	e = list(map(int, input().split()))
	r = []
	for i in e:
		if i == 1:
			print(0, end=' ')
			continue
		j = i - 1
		if w[j] == 999999:
			print(-1, end=' ')
		else:
			print(w[j], end=' ')
	print()


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	le = -1
	for i in range(n):
		if A[i] == 1:
			A[i] = 3
			st = i + 1
			while st < n and A[st] != 1:
				if A[st] == 0:
					A[st] = st + 3 - i
				st = st + 1
		elif A[i] == 2:
			A[i] = 3
			st = i - 1
			while st > le:
				if A[st] == 0 or A[st] > i - st + 3:
					A[st] = i - st + 3
				st = st - 1
			le = i
	for i in range(n):
		if A[i] == 0:
			A[i] = -1
		else:
			A[i] -= 3
	A[0] = 0
	for i in B:
		print(A[i - 1], end=' ')
	print('')


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	max = 1000000000
	mp = []
	for i in range(n):
		if i == 0:
			mp.append(0)
		elif a[i] != 0:
			mp.append(0)
		else:
			mp.append(max)
	ri = -1
	for i in range(n):
		if a[i] == 1:
			ri = i
		if ri != -1:
			if a[i] == 0:
				mp[i] = min(mp[i], i - ri)
	li = -1
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			li = i
		if li != -1:
			if a[i] == 0:
				mp[i] = min(mp[i], li - i)
	for i in range(m):
		j = b[i] - 1
		if mp[j] != max:
			print(mp[j], end=' ')
		else:
			print(-1, end=' ')
	print('')


T = int(input())

def optimumtime(a, b):
	if a == -1:
		return b
	elif b == -1:
		return a
	return min(a, b)
for _ in range(T):
	(N, M) = map(int, input().strip().split())
	A = list(map(int, input().strip().split()))
	B = list(map(int, input().strip().split()))
	A1 = []
	A2 = []
	count1 = -1
	count2 = -1
	for i in range(N):
		cur = A[i]
		revcur = A[N - 1 - i]
		if cur == 1:
			count1 = 0
		if revcur == 2:
			count2 = 0
		A1.append(count1)
		A2.append(count2)
		if count1 != -1:
			count1 += 1
		if count2 != -1:
			count2 += 1
	A2.reverse()
	for (idx, passenger) in enumerate(B):
		if passenger == 1:
			print('0', end=' ')
			continue
		desttime = optimumtime(A1[passenger - 1], A2[passenger - 1])
		print(desttime, end=' ')
	print()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lst = list(map(int, input().split()))
	cases = list(map(int, input().split()))
	(left, right) = ([], [])
	(one, two) = (-1, -1)
	max = 1000000000
	for i in range(n):
		if lst[i] == 1:
			right.append(0)
			one = i
		elif one == -1:
			right.append(max)
		elif lst[i] == 2:
			right.append(0)
		else:
			right.append(i - one)
	for i in range(n - 1, -1, -1):
		if lst[i] == 2:
			left.append(0)
			two = i
		elif two == -1 and lst[i] == 0:
			left.append(max)
		elif lst[i] == 1:
			left.append(0)
		else:
			left.append(two - i)
	left.reverse()
	for i in range(m):
		curr = cases[i]
		if lst[0] != 0 and lst[curr - 1] != 0:
			print('0', end=' ')
		elif curr == 1:
			print('0', end=' ')
		else:
			ans = 0
			if right[curr - 1] == max and left[curr - 1] == max:
				ans = -1
			else:
				ans = min(right[curr - 1], left[curr - 1])
			print(ans, end=' ')
	print()


t = int(input())
while t > 0:
	minval = float('inf')
	maxval = float('-inf')
	(n, m) = map(int, input().split())
	v = []
	q = []
	one = []
	two = []
	v = list(map(int, input().split()))
	q = list(map(int, input().split()))
	for i in range(n):
		one.append(0)
	for i in range(n):
		two.append(0)
	for i in range(n - 1, -1, -1):
		if v[i] == 2:
			minval = min(minval, i)
		elif v[i] == 0:
			if minval != float('inf'):
				one[i] = minval - i
			else:
				one[i] = -1
	for i in range(n):
		if v[i] == 1:
			maxval = max(maxval, i)
		elif v[i] == 0:
			if maxval != float('-inf'):
				two[i] = i - maxval
			else:
				two[i] = -1
	for i in range(m):
		if q[i] == 1:
			print(0, end=' ')
			continue
		if v[q[i] - 1] != 0:
			print(0, end=' ')
		elif one[q[i] - 1] >= 0 and two[q[i] - 1] >= 0:
			print(min(one[q[i] - 1], two[q[i] - 1]), end=' ')
		else:
			print(max(one[q[i] - 1], two[q[i] - 1]), end=' ')
	print()
	t -= 1


try:
	t = int(input())
	for _ in range(t):
		n = input()
		nl = list(map(int, input().strip().split()))
		ml = list(map(int, input().strip().split()))
		nla = []
		x = 'a'
		for i in range(len(nl)):
			if nl[i] == 1:
				x = i
			if x == 'a':
				nla.append(999999)
			else:
				nla.append(i - x)
		nra = []
		nl.reverse()
		x = 'a'
		for i in range(len(nl)):
			if nl[i] == 2:
				x = i
			if x == 'a':
				nra.append(999999)
			else:
				nra.append(i - x)
		nra.reverse()
		nl.reverse()
		ans = []
		for i in ml:
			if i == 1:
				ans.append(0)
			elif nl[i - 1] > 0:
				ans.append(0)
			else:
				k = min(nla[i - 1], nra[i - 1])
				if k == 999999:
					ans.append(-1)
				else:
					ans.append(k)
		y = ''
		for i in ans:
			y = y + ' ' + str(i)
		print(y[1:])
except:
	pass


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().strip().split()))
	b = list(map(int, input().strip().split()))
	maxi = 300000.0 + 5
	t = [0] * n
	low = -1
	high = -1
	for i in range(n):
		if i == 0:
			t[i] = 0
		elif a[i] != 0:
			t[i] = 0
		else:
			t[i] = maxi
	for i in range(n):
		if a[i] == 1:
			high = i
		if high != -1:
			if a[i] == 0:
				t[i] = min(t[i], i - high)
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			low = i
		if low != -1:
			if a[i] == 0:
				t[i] = min(t[i], low - i)
	for i in range(m):
		j = b[i] - 1
		if t[j] != maxi:
			print(t[j])
		else:
			print(-1, end=' ')


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	a.insert(0, 0)
	b.insert(0, 0)
	fleft = [0 for i in range(n + 1)]
	fright = [0 for i in range(n + 1)]
	diffrem = [0 for i in range(n + 1)]
	flag = 1000000
	for i in range(1, n + 1):
		if a[i] == 1:
			fleft[i] = i
			flag = i
		else:
			fleft[i] = flag
	flag = 1000000
	for i in range(n, 0, -1):
		if a[i] == 2:
			fright[i] = i
			flag = i
		else:
			fright[i] = flag
	for i in range(1, n + 1):
		diffrem[i] = min(abs(i - fleft[i]), abs(i - fright[i]))
	for i in range(1, m + 1):
		if b[i] == 1:
			print(0, end=' ')
		elif diffrem[b[i]] == abs(1000000 - b[i]):
			print(-1, end=' ')
		else:
			print(diffrem[b[i]], end=' ')
	print()


T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	n = list(map(int, input().split()))
	m = list(map(int, input().split()))
	l = []
	count = -1
	for i in n:
		if i == 1:
			l.append(0)
			count = 0
			count = count + 1
		elif count == -1:
			l.append(1000000)
		else:
			l.append(count)
			count = count + 1
	count1 = -1
	l1 = []
	for j in range(N - 1, -1, -1):
		if n[j] == 2:
			l1.append(0)
			count1 = 0
			count1 = count1 + 1
		elif count1 == -1:
			l1.append(1000000)
		else:
			l1.append(count1)
			count1 = count1 + 1
	l1.reverse()
	ans = []
	for k in range(N):
		if l[k] <= l1[k]:
			ans.append(l[k])
		elif l[k] == 1000000 and l1[k] == 1000000:
			ans.append(-1)
		else:
			ans.append(l1[k])
	for z in m:
		if z == 1:
			print(0)
		elif ans[z - 1] == 1000000:
			print(-1, end=' ')
		else:
			print(ans[z - 1], end=' ')
	print()


t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	max = 10 ** 9
	newArray = [None] * n
	newArray[0] = 0
	for i in range(1, n):
		if a[i] != 0:
			newArray[i] = 0
		else:
			newArray[i] = max
	r = -1
	for i in range(n):
		if a[i] == 1:
			r = i
		if r != -1:
			if a[i] == 0:
				newArray[i] = min(newArray[i], i - r)
	l = -1
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			l = i
		if l != -1:
			if a[i] == 0:
				newArray[i] = min(newArray[i], l - i)
	for i in range(m):
		x = b[i] - 1
		if newArray[x] != max:
			print(newArray[x], end=' ')
		else:
			print(-1, end=' ')
	print()


from collections import defaultdict as dd
for _ in range(int(input())):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	lside = [float('-inf')]
	rside = [float('inf')]
	for x in range(len(A)):
		if A[x] == 1:
			lside.append(x)
		else:
			lside.append(lside[-1])
	for x in range(len(A) - 1, -1, -1):
		if A[x] == 2:
			rside.append(x)
		else:
			rside.append(rside[-1])
	rside.reverse()
	rside.pop()
	lside = lside[1:]
	ans = []
	for dest in B:
		dest -= 1
		if A[dest] != 0 or dest == 0:
			ans.append('0')
		else:
			neaanst_lside = dest - lside[dest]
			neaanst_rside = rside[dest] - dest
			dist = min(neaanst_lside, neaanst_rside)
			if dist == float('inf') or dist == float('-inf'):
				ans.append('-1')
			else:
				ans.append(str(dist))
	print(' '.join(ans))


T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split(' '))
	A = list(map(int, input().split(' ')[:N]))
	B = list(map(int, input().split(' ')[:M]))
	la = [None] * N
	la[0] = 0
	mx = 10 ** 9
	for i in range(1, N):
		if A[i] != 0:
			la[i] = 0
		else:
			la[i] = mx
	right = -1
	for i in range(N):
		if A[i] == 1:
			right = i
		if right != -1:
			if A[i] == 0:
				la[i] = min(la[i], i - right)
	left = -1
	for i in range(N - 1, 0, -1):
		if A[i] == 2:
			left = i
		if left != -1:
			if A[i] == 0:
				la[i] = min(la[i], left - i)
	for i in range(M):
		x = B[i] - 1
		if la[x] != mx:
			print(la[x], end=' ')
		else:
			print(-1, end=' ')
	print()


for t in range(int(input())):
	t1 = -1
	t2 = -1
	ma = int(1000000000.0)
	(n, m) = map(int, input().split())
	arr1 = list(map(int, input().split()))
	arr2 = list(map(int, input().split()))
	mp = {}
	for i in range(n):
		if i == 0:
			mp[i] = 0
		elif arr1[i] != 0:
			mp[i] = 0
		else:
			mp[i] = ma
	for i in range(n):
		k = arr1[i]
		if k == 1:
			t1 = i
		if t1 != -1:
			if k == 0:
				mp[i] = min(mp[i], i - t1)
	for i in range(n - 1, -1, -1):
		k = arr1[i]
		if k == 2:
			t2 = i
		if t2 != -1:
			if arr1[i] == 0:
				mp[i] = min(mp[i], t2 - i)
	ans = []
	for i in range(m):
		if mp[arr2[i] - 1] != ma:
			ans.append(str(mp[arr2[i] - 1]))
		else:
			ans.append(str(-1))
	print(' '.join(ans))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	p = [0] * n
	q = [0] * n
	for i in range(n):
		if a[i] == 1:
			p[i] = 1
		else:
			p[i] = 0
	for i in range(n):
		if a[i] == 2:
			q[i] = 2
		else:
			q[i] = 0
	s = [-3] * n
	for i in range(n):
		if a[i] == 1:
			s[i] = 0
	s[0] = 0
	for i in range(1, n):
		if s[i] == -3:
			if i != 1:
				if s[i - 1] == -1:
					s[i] = -1
				else:
					s[i] = s[i - 1] + 1
			elif a[0] == 1:
				s[i] = 1
			else:
				s[i] = -1
	t = [-3] * n
	for i in range(n):
		if a[i] == 2:
			t[i] = 0
	t[0] = 0
	if a[n - 1] == 0 or a[n - 1] == 1:
		t[n - 1] = -1
	else:
		t[n - 1] = 0
	for i in range(n - 2, 0, -1):
		if t[i] == -3:
			if t[i + 1] == -1:
				t[i] = -1
			else:
				t[i] = t[i + 1] + 1
	for i in range(n):
		if a[i] == 1:
			t[i] = 0
	for i in range(n):
		if a[i] == 2:
			s[i] = 0
	v = [-3] * n
	for i in range(n):
		if a[i] != 0:
			v[i] = 0
	for i in range(n):
		if v[i] == -3:
			if s[i] == -1 and t[i] == -1:
				v[i] = -1
			elif s[i] != -1 and t[i] == -1:
				v[i] = s[i]
			elif s[i] == -1 and t[i] != -1:
				v[i] = t[i]
			else:
				v[i] = min(s[i], t[i])
	for i in range(m):
		r = b[i] - 1
		print(v[r], end=' ')
	print()


import sys
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	ans = [None] * n
	ans[0] = 0
	max = 10 ** 9
	for i in range(1, n):
		if a[i] != 0:
			ans[i] = 0
		else:
			ans[i] = max
	j = -1
	for i in range(n):
		if a[i] == 1:
			j = i
		if j != -1:
			if a[i] == 0:
				ans[i] = min(ans[i], i - j)
	j = -1
	for i in range(n - 1, 0, -1):
		if a[i] == 2:
			j = i
		if j != -1:
			if a[i] == 0:
				ans[i] = min(ans[i], j - i)
	for i in range(m):
		j = b[i] - 1
		if ans[j] == max:
			print(-1, end=' ')
		else:
			print(ans[j], end=' ')
	print()


from bisect import bisect_left
for _ in range(int(input())):
	(n, m) = (int(x) for x in input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	(ls, rs) = ([], [])
	for (i, x) in enumerate(a):
		if x == 1:
			rs.append(i + 1)
		elif x == 2:
			ls.append(i + 1)
	for x in b:
		(t, u) = (bisect_left(rs, x), bisect_left(ls, x))
		st = set()
		if rs:
			if t == 0 and rs[t] == x:
				st.add(0)
			if t != 0 and t < len(rs):
				st.add(0 if rs[t] == x else x - rs[t - 1])
			elif t:
				st.add(x - rs[t - 1])
		if ls:
			if u < len(ls):
				st.add(ls[u] - x)
		if x == 1:
			print(0, end=' ')
		elif st:
			print(min(st), end=' ')
		else:
			print(-1, end=' ')
	print()


tc = int(input())
for _ in range(tc):
	(n, m) = map(int, input().split(' '))
	arr = list(map(int, input().split(' ')))
	answer = list(map(int, input().split(' ')))
	left = [0] * n
	right = [0] * n
	mn = -1
	mn = 'OUT'
	for i in range(n):
		if arr[i] == 1:
			left[i] = i
			mn = i
		elif arr[i] == 2:
			left[i] = i
		else:
			left[i] = mn
	mx = 'OUT'
	for i in range(n - 1, -1, -1):
		if arr[i] == 1:
			right[i] = i
		elif arr[i] == 2:
			right[i] = i
			mx = i
		else:
			right[i] = mx
	for item in answer:
		item = item - 1
		if item == 0:
			print(0, end=' ')
		elif arr[item] == 1 or arr[item] == 2:
			print(0, end=' ')
		elif left[item] == 'OUT' and right[item] == 'OUT':
			print('-1', end=' ')
		elif left[item] == 'OUT':
			temp = abs(right[item] - item)
			print(temp, end=' ')
		elif right[item] == 'OUT':
			temp = abs(left[item] - item)
			print(temp, end=' ')
		else:
			temp = min(abs(left[item] - item), abs(right[item] - item))
			print(temp, end=' ')
	print()


import sys
import time

def timebata():
	return time.perf_counter()

def lis_in():
	a = list(map(int, input().split()))
	return a

def len_arr(a):
	return len(a)

def fir_0(arr):
	arr[0] = 0
	return arr

def check_zero(a):
	if a == 0:
		return True
	else:
		return False

def check_one(arr, i):
	if arr[i] == 1:
		return True
	else:
		return False

def check_m_one(a):
	if a == -1:
		return True
	return False

def check_two(arr, i):
	if arr[i] == 2:
		return True
	else:
		return False
for pp in range(int(input())):
	(n, m) = map(int, input().split())
	arr = lis_in()
	x1 = timebata()
	query = lis_in()
	nn = len_arr(arr)
	left_array = []
	for i in range(nn):
		left_array.append(-1)
	left_array = fir_0(left_array)
	currmax = -1
	for i in range(nn):
		if check_one(arr, i):
			currmax = i
		if check_m_one(currmax):
			left_array[i] = -1
		if check_m_one(currmax) == False:
			left_array[i] = i - currmax
	right_array = []
	for i in range(nn):
		right_array.append(-1)
	currmin = -1
	for i in range(len(arr) - 1, -1, -1):
		if check_two(arr, i):
			currmin = i
		if check_m_one(currmin):
			right_array[i] = -1
		if check_m_one(currmin) == False:
			right_array[i] = currmin - i
	x5 = timebata()
	result = []
	for q in query:
		x2 = timebata()
		q -= 1
		if check_zero(q):
			result.append(0)
			continue
		if right_array[q] == -1:
			lulu = left_array[q]
			result.append(lulu)
		elif left_array[q] == -1:
			lulu = right_array[q]
			result.append(lulu)
		else:
			lulu = min(right_array[q], left_array[q])
			x3 = timebata()
			result.append(lulu)
	print(*result, sep=' ')


for test in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	maxx = float('inf')
	listt = dict()
	for i in range(n):
		if i == 0 or a[i] != 0:
			listt[i] = 0
		else:
			listt[i] = maxx
	righty = -10
	for i in range(n):
		if a[i] == 1:
			righty = i
		if righty != -10 and a[i] == 0:
			listt[i] = min(listt[i], i - righty)
	lefty = -10
	for i in range(n - 1, -1, -1):
		if a[i] == 2:
			lefty = i
		if lefty != -10 and a[i] == 0:
			listt[i] = min(listt[i], lefty - i)
	for i in range(m):
		if listt[b[i] - 1] != maxx:
			print(listt[b[i] - 1], end=' ')
		else:
			print('-1', end=' ')
	print()