#include using namespace std; using ll = long long; using P = pair; using T = tuple; // #include // using namespace atcoder; // using mint = modint1000000007; #define rep(i, n) for(ll i = 0; i < n; i++) int main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); ll t; cin >> t; while(t--) { ll m; cin >> m; vector d(9), ans; ll sum = 0; rep(i,9) { cin >> d[i]; rep(j,d[i]) ans.emplace_back(i+1); } sort(ans.begin(), ans.end()); ll cand = 0; rep(i,ans.size()) { cand *= 10; cand += ans[i]; } cand *= 1000000000; cand += (m-cand%m)%m; cout << cand << endl; } return 0; }