#include <bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
using namespace std;
namespace ywy {
inline int get() {
  int n = 0;
  char c;
  while ((c = getchar()) || 23333)
    if (c >= '0' && c <= '9') break;
  n = c - '0';
  while ((c = getchar()) || 23333) {
    if (c >= '0' && c <= '9')
      n = n * 10 + c - '0';
    else
      return n;
  }
}
long long dp[1000010], val[10];
void ywymain() {
  int k = get(), f0 = get(), f1 = get(), f2 = get(), f3 = get(), f4 = get(),
      f5 = get();
  val[0] = f0;
  val[1] = f1;
  val[2] = f2;
  val[3] = f3;
  val[4] = f4;
  val[5] = f5;
  for (int i = 0; i < 1000000; i++) {
    int tmp = i;
    for (int j = 0; j < 6; j++, tmp /= 10) {
      if ((tmp % 10) % 3 == 0) dp[i] += val[j] * (long long)((tmp % 10) / 3);
    }
  }
  if (k > 1) {
    for (int i = 0, dk = 1; i < 6; i++, dk *= 10) {
      int rest = 3 * (k - 1);
      for (int j = 0; j <= 23; j++) {
        if ((1 << j) <= rest) {
          rest -= (1 << j);
          for (int x = 999999; x >= (3ll * dk) * (1ll << j); x--)
            dp[x] = max(dp[x], dp[x - 3 * dk * (1 << j)] + val[i] * (1ll << j));
        }
      }
      if (rest) {
        for (int x = 999999; x >= (3ll * dk) * rest; x--)
          dp[x] = max(dp[x], dp[x - 3 * dk * rest] + val[i] * (long long)rest);
      }
    }
  }
  int q = get();
  while (q--) printf("%lld\n", dp[get()]);
}
}  // namespace ywy
int main() {
  ywy::ywymain();
  return 0;
}
