// #include #include using namespace std; using namespace atcoder; using ll = long long; #define rep(i, n) for (int i=0; i<(int)(n); ++(i)) #define rep3(i, m, n) for (int i=(m); (i)<(int)(n); ++(i)) #define repr(i, n) for (int i=(int)(n)-1; (i)>=0; --(i)) #define rep3r(i, m, n) for (int i=(int)(n)-1; (i)>=(int)(m); --(i)) #define all(x) (x).begin(), (x).end() const int INF = (int)(1e9); int main() { int t0; cin >> t0; rep(i0, t0) { int m; cin >> m; vector d(10); rep3(i, 1, 10) cin >> d[i]; if (accumulate(all(d), 0) == 0) { cout << m << endl; continue; } string s; rep3(i, 1, 10) s += string(d[i], '0'+i); int ten = 0, tar = 1; ll x = 0; while (1) { int mval = (m - stoll(s+string(ten,'0')) % m) % m; if (mval < tar) { x = stoll(s+string(ten,'0')) + mval; break; } ++ten; tar *= 10; } cout << x << endl; } return 0; }