#include <bits/stdc++.h>
const int BIT = 6;
const int N = 1000010;
using ll = long long;
int f[BIT];
ll dp[2][N];
int bit[BIT];
int divide(int a, int b) { return a / b - (a % b != 0 && (a < 0 ^ b < 0)); }
void solve(int k) {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < BIT; ++i) {
    bit[i] = n % 10;
    n /= 10;
  }
  memset(dp, -1, sizeof(dp));
  dp[0][bit[BIT - 1]] = 0;
  for (int i = BIT - 1; i >= 0; --i) {
    int one = 0;
    for (int j = 0; j < i; ++j) {
      one = one * 10 + 9;
    }
    std::deque<int> deque[3];
    auto get = [&](int pos, int mod) {
      return dp[0][pos] + 1ll * f[i] * divide(pos - mod, 3);
    };
    memset(dp[1], -1, sizeof(dp[1]));
    for (int j = N - 1; j >= 0; --j) {
      int ban = 9 * (k - 1) + j + 1;
      for (int u = 0; u < 3; ++u) {
        if (!deque[u].empty() && deque[u].front() == ban) {
          deque[u].pop_front();
        }
      }
      if (dp[0][j] != -1) {
        for (int u = 0; u < 3; ++u) {
          while (!deque[u].empty() && get(deque[u].back(), u) <= get(j, u)) {
            deque[u].pop_back();
          }
          deque[u].push_back(j);
        }
      }
      int mod = j % 3;
      if (!deque[mod].empty()) {
        int pos = deque[mod].front();
        dp[1][j] = get(pos, j);
      }
      for (int u = ban; u <= ban + 9 - 1 && u < N; ++u) {
        if (dp[0][u] == -1) {
          continue;
        }
        ll value;
        if ((u - j) % 3 == 0) {
          value = dp[0][u] + 1ll * f[i] * divide(u - j, 3);
        } else {
          value = dp[0][u] + 3ll * f[i] * divide(u - j, 9);
        }
        dp[1][j] = std::max(dp[1][j], value);
      }
    }
    memset(dp[0], -1, sizeof(dp[0]));
    for (int j = 0; j < N; ++j) {
      if (dp[1][j] != -1) {
        int pos = j * 10 + (i ? bit[i - 1] : 0);
        if (pos >= N) {
          continue;
        }
        dp[0][pos] = dp[1][j];
      }
    }
  }
  printf("%lld\n", dp[0][0]);
}
int main() {
  int k;
  scanf("%d", &k);
  for (int i = 0; i < BIT; ++i) {
    scanf("%d", &f[i]);
  }
  int test;
  scanf("%d", &test);
  while (test--) {
    solve(k);
  }
}
