#include <bits/stdc++.h>
using namespace std;
const int M = 1e6;
long long F[10];
long long f[M + 100];
int main() {
  int k;
  scanf("%d", &k);
  for (int i = 0; i < 6; i++) scanf("%lld", F + i);
  memset(f, 0, sizeof(f));
  for (int i = 0; i < M; i++) {
    int d = 0, x = i;
    while (x) {
      int now = x % 10;
      if (now % 3 == 0) f[i] += F[d] * (now / 3);
      d++;
      x /= 10;
    }
  }
  int base = 3;
  for (int i = 0; i < 6; i++) {
    for (int j = 1; j <= 3; j++) {
      int res = min(k - 1, (M - 1) / base);
      for (int t = 1; t < res; t <<= 1) {
        int d = base * t;
        res -= t;
        for (int p = M - 1; p >= 0; --p) {
          if (p < d) break;
          f[p] = max(f[p], f[p - d] + F[i] * t);
        }
      }
      int d = base * res;
      for (int p = M - 1; p >= 0; --p) {
        if (p < d) break;
        f[p] = max(f[p], f[p - d] + F[i] * res);
      }
    }
    base = base * 10;
  }
  int q;
  scanf("%d", &q);
  while (q--) {
    int n;
    scanf("%d", &n);
    printf("%lld\n", f[n]);
  }
  return 0;
}
