from itertools import permutations def culc(M,d): D = [] for i in range(9): if d[i]!=0: for _ in range(d[i]): D.append(str(i+1)) for perm in permutations(D): s = ''.join(item for item in perm) X = int(s) if X%M==0: return X elif M - ((X*10)%M) < 10: return X*10 + M - ((X*10)%M) T = int(input()) for i in range(T): M = int(input()) d = list(map(int, input().split())) ans = culc(M,d) print(ans) ''' for perm in permutations(D): s = ''.join(perm) X = int(s) if X%M==0: return X '''