class Input_kyopro: def II(self): return int(input()) def MI(self): return map(int,input().split()) def MS(self): return map(str,input().split()) def LMI(self): return list(self.MI()) def LMS(self): return list(self.MS()) def LLI(self,N): return [self.LMI() for _ in range(N)] def LLS(self,N): return [self.LMS() for _ in range(N)] def LS(self,N): return [input() for _ in range(N)] def LSL(self,N): return [list(input()) for _ in range(N)] def LI(self,N): return [self.II() for _ in range(N)] I=Input_kyopro() #入力 T=I.II() for _ in range(T): M=I.II() d=I.LMI() X=0 now=0 for i in range(9): while d[i]: X+=(i+1)*pow(10,17-now) d[i]-=1 now+=1 X+=M-X%M print(X)