#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 6e5+10;
const int INF = 1e18;
int c ,t , n, a[11], cnt[11],tot[11],pos[N][11],last[11];
char s[N];
void init(){
memset(cnt,0,sizeof(cnt));
memset(pos,0,sizeof(pos));
memset(last,0,sizeof(last));
}
void build(){
for(int i = n; i >= 1; i--){
last[s[i] - '0'] = i;
for(int j = 1; j <= 9; j++) pos[i][j] = last[j];
}
}
int check(int x){
string l = to_string(x);
if(l.size() > n) return 0;
for(int i = 0,p = 1; i < l.size(); i++){
int c = l[i] - '0';
if(pos[p][c] == 0) return 0;
p = pos[p][c];
}
return 1;
}
signed main(){
scanf("%lld%lld",&c,&t);
while(t--){
init();
scanf("%s",s+1);
n = strlen(s+1);
build();
for(int i = 1; i <= 9; i++) scanf("%lld",&a[i]);
for(int i = 1; i <= n; i++) cnt[s[i] - '0']++;
int cost = 0,res = INF;
for(int i = 1; i <= 9; i++) cost += a[i] * cnt[i];
for(int i = 0; i <= 1000000; i++){
memset(tot,0,sizeof(tot));
for(int tmp = i; tmp; tmp /= 10) tot[tmp % 10] ++;
if(check(i)){
int ans = cost;
for(int j = 1; j <= 9; j++) ans -= tot[j] * a[j];
res = min(res,ans + i);
}
}
printf("%lld\n",res);
}
}