#include <bits/stdc++.h>
using namespace std;

int main() {

	int n,m;
	cin >> n >> m;
	vector<string > s(n);
	for(int i=0 ; i<n; i++)
	{
	   cin >> s[i];
	}
	int ans=1;
	for(int i=0; i<m; i++)
	{
		set<char >st;
		for(int j=0; j<n; j++)
		{
			st.insert(s[i][j]);
		} ans*=(st.size());
	}
	// your code goes here
	return 0;
}


r=lambda{gets.split.map{|i| i.to_i}}
n,m,k=r.call
a=[]
s=[0]*m
b=[0]*n
n.times{a<<r.call}
k.times{t,q=r.call;s[q-1]+=1;b[t-1]-=1}
n.times{|i| m.times{|j| b[i]+=s[j] if a[i][j]==1}}
puts b.join " "


R=lambda:map(int,raw_input().split())
n,m,k=R()
g=[R() for _ in range(n)]
a=[0]*n
b=[0]*m
for _ in range(k):
  x,y=R()
  a[x-1]+=1
  b[y-1]+=1
print ' '.join(map(str,[sum(g[i][j]*b[j] for j in range(m))-a[i] for i in range(n)]))


from sys import stdin, stdout
def main():
    n, m, k = map(int, stdin.readline().split())
    a = [map(int, stdin.readline().split()) for _ in xrange(n)]
    c = [0] * m
    d = [0] * n
    for _ in xrange(k):
        s, t = map(int, stdin.readline().split())
        s, t = s-1, t-1
        c[t] += 1
        d[s] -= 1
    for i, b in enumerate(a):
        for j, f in enumerate(b):
            d[i] += f * c[j]
    stdout.write(' '.join(map(str, d)))
main()


n, m, k = [int(x) for x in raw_input().split(' ')]
a = [[[bool(int(x)), 0] for x in raw_input().split(' ')] for _ in range(n)]
sums = [0, ] * m

for ki in range(k):
    ni, mi = [int(x) for x in raw_input().split(' ')]
    a[ni - 1][mi - 1][1] += 1
    sums[mi - 1] += 1

for ni in range(n):
    tot = 0
    for mi in range(m):
        if a[ni][mi][0]:
            tot += sums[mi] - a[ni][mi][1]
    print tot,
print ""


import sys
file = sys.stdin

n, m, k = file.readline().split(' ')

n = int(n)
m = int(m)
k = int(k)

a = [[]]*n
for i in range(0, n):
    a[i] = [int(val) for val in file.readline().split(' ')]

ans = [0]*n
chmsg = [0]*m
for i in range(0, k):
    x, y = file.readline().split(' ')
    x = int(x)
    y = int(y)
    chmsg[y-1] += 1
    ans[x-1] -= 1

for i in range(0, n):
    for j in range(0, m):
        if a[i][j] == 1:
            ans[i] += chmsg[j]
    if ans[i] < 0:
        ans[i] = 0

print(" ".join([str(val) for val in ans]))


import sys
n,m,k = [int(x) for x in raw_input().split()]
count = 0
data = []
count = [0 for ele in range(n)]
for i in range(n):
    new_data=[int (x) for x in raw_input().split()]
    data.append(new_data)
for p in range(k):
    x, y = [int(p) for p in raw_input().split()]
    x -= 1
    y -= 1
    for i in range(n):
        if (data[i][y] == 1) and (i != x): count[i] += 1
print count


import sys
n,m,k = [int(x) for x in raw_input().split()]
count = 0
data = []
count = [0] * n
for i in range(n):
    new_data=[int (x) for x in raw_input().split()]
    data.append(new_data)
for p in range(k):
    x, y = [int(p) for p in raw_input().split()]
    x -= 1
    y -= 1
    for i in range(n):
        if (data[i][y] == 1) and (i != x): count[i] += 1
print count


import sys
n,m,k = [int(x) for x in raw_input().split()]
count = 0
data = []
count = [0] * m
for i in range(n):
    new_data=[int (x) for x in raw_input().split()]
    data.append(new_data)
for p in range(k):
    x, y = [int(p) for p in raw_input().split()]
    x -= 1
    y -= 1
    count[y] += 1
    data[x][y] += 1
res = []
for x in range(n):
    sum = 0
    for y in range(m):
        if data[x][y]:
            sum += count[y] - data[x][y] + 1
    res.append(sum)
print ' '.join(str(x) for x in res)


import sys
n,m,k = [int(x) for x in raw_input().split()]
count = 0
data = []
count = [0] * n
for i in range(n):
    new_data=[int (x) for x in raw_input().split()]
    data.append(new_data)
for p in range(k):
    x, y = [int(p) for p in raw_input().split()]
    x -= 1
    y -= 1
    for i in range(n):
        if (data[i][y] == 1) and (i != x): count[i] += 1
print ' '.join( str(x) for x in count)


[n, m, k] = [int(x) for x in raw_input().split(" ")]
mat = [[] for x in xrange(m)]
for i in xrange(n):
    line = raw_input().split(" ")
    for idx, j in enumerate(line):
        if j == "1":
            mat[idx].append(i)
res = [0 for x in xrange(n)]
for i in xrange(k):
    [x, y] = [int(x)-1 for x in raw_input().split(" ")]
    for j in mat[y]:
        res[j] += 1
    res[x] -= 1
print ' '.join([str(x) for x in res])


n, m, k = map(int, raw_input().split())
mat = [[] for x in xrange(m)]
for i in xrange(n):
    line = raw_input().split(" ")
    for idx, j in enumerate(line):
        if j == "1":
            mat[idx].append(i)
res = [0 for x in xrange(n)]
nn = [0 for x in xrange(n)]
mm = [0 for x in xrange(m)]
for i in xrange(k):
    x, y = map(int, raw_input().split())
    nn[x-1] += 1
    mm[x-1] += 1
for idx, x in enumerate(mm):
    for y in mat[idx]:
        res[y] += x
for idx, x in enumerate(nn):
    res[idx] -= x
print ' '.join([str(x) for x in res])


n, m, k = map(int, raw_input().split())
mat = [[] for x in xrange(m)]
for i in xrange(n):
    line = raw_input().split(" ")
    for idx, j in enumerate(line):
        if j == "1":
            mat[idx].append(i)
res = [0 for x in xrange(n)]
nn = [0 for x in xrange(n)]
mm = [0 for x in xrange(m)]
for i in xrange(k):
    x, y = map(int, raw_input().split())
    nn[x-1] += 1
    mm[y-1] += 1
for idx, x in enumerate(mm):
    for y in mat[idx]:
        res[y] += x
for idx, x in enumerate(nn):
    res[idx] -= x
print ' '.join([str(x) for x in res])


[n, m, k] = [int(x) for x in raw_input().strip().split(" ")]
mat = [[0 for x in xrange(m)] for y in xrange(n)]
for i in range(n):
    mat[i] = [int(x) for x in raw_input().strip().split(" ")]
res = [0 for x in xrange(n)]
for i in range(k):
    [x, y] = [int(x) for x in raw_input().strip().split(" ")]
    x -= 1
    y -= 1
    for j in range(n):
        if x != j and mat[j][y] == 1:
            res[j] += 1
print ' '.join([str(x) for x in res])


[n, m, k] = [int(x) for x in raw_input().split(" ")]
mat = [list() for x in xrange(m)]
for i in xrange(n):
    line = [int(x) for x in raw_input().split(" ")]
    for idx, j in enumerate(line):
        if j == 1:
            mat[idx].append(i)
res = [0 for x in xrange(n)]
for i in xrange(k):
    [x, y] = [int(x)-1 for x in raw_input().split(" ")]
    for j in mat[y]:
        res[j] += 1
    res[x] -= 1
print ' '.join([str(x) for x in res])


[n, m, k] = [int(x) for x in raw_input().strip().split(" ")]
mat = [list() for x in xrange(m)]
for i in range(n):
    line = [int(x) for x in raw_input().strip().split(" ")]
    for idx, j in enumerate(line):
        if j == 1:
            mat[idx].append(i)
res = [0 for x in xrange(n)]
for i in range(k):
    [x, y] = [int(x)-1 for x in raw_input().strip().split(" ")]
    for j in mat[y]:
        res[j] += 1
    res[x] -= 1
print ' '.join([str(x) for x in res])


n, m, k = map(int, raw_input().split())
mat = [[] for x in xrange(m)]
for i in xrange(n):
    line = raw_input().split(" ")
    for idx, j in enumerate(line):
        if j == "1":
            mat[idx].append(i)
res = [0 for x in xrange(n)]
for i in xrange(k):
    x, y = map(int, raw_input().split())
    x -= 1
    y -= 1
    for j in mat[y]:
        res[j] += 1
    res[x] -= 1
print ' '.join([str(x) for x in res])


n, m, k = map(int, raw_input().split())
a = [map(int, raw_input().split()) for _ in range(n)]
c, s = [0] * m, [0] * n
for _ in range(k):
	x, y = map(lambda x: int(x) - 1, raw_input().split())
	s[x], c[y] = s[x] + 1, c[y] + 1
for i in range(n):
	print sum(a[i][j] * c[j] for j in range(m)) - s[i],


n,m,k=map(int,raw_input().split())
a=[]
chat=[0]*m
mes=[0]*n
for i in range(n):
    a.append(map(int,raw_input().split()))
for k in range(k):
    x,y=map(int,raw_input().split())
    chat[y]+=1
    mes[x]-=1
for i in range(n):
    for j in range(m):
        if a[i][j]==1:
            mes[i]+=chat[j]
    print mes[i],
print "\n"

##n,m,mini,maxi=map(int,raw_input().split())
##t=map(int,raw_input().split())
##t=sorted(t)
##needed=n-m
##if t[0]>=mini and t[-1]<=maxi:
##    if needed>=2:
##        print "Correct"
##    elif needed==1:
##        if  mini==t[0] or maxi==t[-1]:
##            print "Correct"
##        else:
##            print "Incorrect"
##    elif n-m==0 and t[0]==mini and t[-1]==maxi:
##        print "Correct"
##    else:
##        print "Incorrect"
##
##else:
##    print "Incorrect"


n,m,k=map(int,raw_input().split())
a=[]
chat=[0]*m
mes=[0]*n
for i in range(n):
    a.append(map(int,raw_input().split()))
#print a
for k in range(k):
    x,y=map(int,raw_input().split())
    chat[y]+=1
    mes[x]-=1
for i in range(n):
    for j in range(m):
        if a[i][j]==1:
            mes[i]+=chat[j]
    print mes[i],
print "\n"

##n,m,mini,maxi=map(int,raw_input().split())
##t=map(int,raw_input().split())
##t=sorted(t)
##needed=n-m
##if t[0]>=mini and t[-1]<=maxi:
##    if needed>=2:
##        print "Correct"
##    elif needed==1:
##        if  mini==t[0] or maxi==t[-1]:
##            print "Correct"
##        else:
##            print "Incorrect"
##    elif n-m==0 and t[0]==mini and t[-1]==maxi:
##        print "Correct"
##    else:
##        print "Incorrect"
##
##else:
##    print "Incorrect"


n,m,k=map(int,raw_input().split())
a=[]
chat=[0]*m
mes=[0]*n
for i in range(n):
    a.append(map(int,raw_input().split()))
#print a
for k in range(k):
    x,y=map(int,raw_input().split())
    chat[y-1]+=1
    mes[x-1]-=1
for i in range(n):
    for j in range(m):
        if a[i][j]==1:
            mes[i]+=chat[j]
    print mes[i],
print ""

##n,m,mini,maxi=map(int,raw_input().split())
##t=map(int,raw_input().split())
##t=sorted(t)
##needed=n-m
##if t[0]>=mini and t[-1]<=maxi:
##    if needed>=2:
##        print "Correct"
##    elif needed==1:
##        if  mini==t[0] or maxi==t[-1]:
##            print "Correct"
##        else:
##            print "Incorrect"
##    elif n-m==0 and t[0]==mini and t[-1]==maxi:
##        print "Correct"
##    else:
##        print "Incorrect"
##
##else:
##    print "Incorrect"


vals=[int(x) for x in raw_input().split()]
n=vals[0]
m=vals[1]
k=vals[2]
cc=[[int(x) for x in raw_input().split()] for i in range(n)]
nn=[0 for q in range(n)]
mm=[0 for q in range(m)]
for i in range(k):
    vals=[int(x)-1 for x in raw_input().split()]
    nn[vals[0]]+=1
    mm[vals[1]]+=1

aa=[]
for i in range(n):
    a=0
    for j in range(m):
        if cc[i][j]:
            a+=mm[j]
    aa.append(a-nn[i])

print(' '.join([str(x) for x in aa]))


vals=[int(x) for x in raw_input().split()]
n=vals[0]
m=vals[1]
k=vals[2]
cc=[[int(x) for x in raw_input().split()] for i in range(n)]
mm=[0 for q in range(n)]
for i in range(k):
    vals=[int(x)-1 for x in raw_input().split()]
    u=vals[0]
    c=vals[1]
    for j in range(n):
        if cc[j][c] and j!=u:
            mm[j]+=1

print(' '.join([str(x) for x in mm]))


vals=[int(x) for x in raw_input().split()]
n=vals[0]
m=vals[1]
k=vals[2]
cc=[[int(x) for x in raw_input().split()] for i in range(n)]
mm=[0 for q in range(n)]
for i in range(k):
    vals=[int(x)-1 for x in raw_input().split()]
    u=vals[0]
    c=vals[1]
    for j in range(n):
        if j!=u:
            mm[j]+=cc[j][c]

print(' '.join([str(x) for x in mm]))


a,b,k = map(int, raw_input().split())
employee = []
for i in range(a):
	line = map(int, raw_input().split())
	room = []
	for x in range(b):
		if (line[x] == 1):
			room.append(x + 1)
	employee.append(room)

room_log = {key: 0 for key in range(1, b + 1)}
employee_log = {key: 0 for key in range(1, a + 1)}

for i in range(k):
	e, p = map(int, raw_input().split())
	room_log[p] += 1
	employee_log[e] += 1

for i in range(a):
	answer = 0
	for room in employee[i]:
		answer += room_log[room]
	print answer - employee_log[i + 1],


import time

start = time.time()
a,b,k = map(int, raw_input().split())
employee = []
for i in range(a):
	line = map(int, raw_input().split())
	room = []
	for x in range(b):
		if (line[x] == 1):
			room.append(x + 1)
	employee.append(room)

room_log = {key: 0 for key in range(1, b + 1)}
employee_log = {key: 0 for key in range(1, a + 1)}

for i in range(k):
	e, p = map(int, raw_input().split())
	room_log[p] += 1
	employee_log[e] += 1

for i in range(a):
	answer = 0
	for room in employee[i]:
		answer += room_log[room]
	print answer - employee_log[i + 1],
print
print time.time()-start


x=raw_input().split()
n=int(x[0])
m=int(x[1])
k=int(x[2])
lis=[]
mes=[0]*n
roinvo=[0]*m
for i in range(n):
    x=raw_input().split()
    for i in range(len(x)):
        x[i]=int(x[i])
    lis.append(x)
for i in range(k):
    x=raw_input().split()
    roinvo[int(x[1])-1]+=1
    mes[int(x[0])-1]-=1
for i in range(n):
    for k in range(m):
        mes[i]+=roinvo[k]*lis[i][k]
for i in mes:
    print i,


x=raw_input().split()
n=int(x[0])
m=int(x[1])
k=int(x[2])
lis=[]
for i in range(n):
    x=raw_input().split()
    for i in range(len(x)):
        x[i]=int(x[i])
    lis.append(x)
mes=[0]*n
for i in range(k):
    x=raw_input().split()
    p=int(x[0])
    q=int(x[1])
    for i in range(n):
        if lis[i][q-1]==1 and i!=p-1:
            mes[i]+=1
for i in mes:
    print i,


#Author: squiggly_lines
#Date: 31/05/2014
#Problem: 413B
import operator
def main():
    n,m,k = map(int, raw_input().split())

    a = []

    for i in xrange(n):
        a.append(map(int, raw_input().split()))

    chat_received = [0 for i in xrange(m)]
    person_sent = [0 for i in xrange(n)]
    for i in xrange(k):
        x,y = map(int, raw_input().split())
        chat_received[y-1] += 1
        person_sent[x-1] += 1

    for i in xrange(n):
        print sum(map(operator.__mul__, a[i], chat_received))-person_sent[i],

if __name__ == "__main__":
    main()


#Author: squiggly_lines
#Date: 31/05/2014
#Problem: 413B
from collections import defaultdict
def main():
    n,m,k = map(int, raw_input().split())

    a = []
    for i in xrange(n):
        a.append(map(int, raw_input().split()))

    chat = defaultdict(set)
    for i in xrange(n):
        for j in xrange(m):
            if a[i][j] == 1:
                chat[j+1].add(i+1)

    messages = defaultdict(lambda: 0)

    for i in xrange(k):
        x,y = map(int, raw_input().split())
        for member in chat[y]:
            if not member == x:
                messages[member] += 1

    for i in xrange(1,n+1):
        print messages[i],

if __name__ == "__main__":
    main();


#Author: squiggly_lines
#Date: 31/05/2014
#Problem: 413B
from collections import defaultdict

def main():
    n,m,k = map(int, raw_input().split())

    a = []
    chat = defaultdict(set)
    for i in xrange(n):
        t = map(int, raw_input().split())
        for j in xrange(m):
            if t[j] == 1:
                chat[j+1].add(i+1)

    messages = defaultdict(int)

    for i in xrange(k):
        x,y = map(int, raw_input().split())
        for member in chat[y]:
            if not member == x:
                messages[member] += 1

    for i in xrange(1,n+1):
        print messages[i],

if __name__ == "__main__":
    main()


#Author: squiggly_lines
#Date: 31/05/2014
#Problem: 413B

def main():
    n,m,k = map(int, raw_input().split())

    a = []

    for i in xrange(n):
        a.append(map(int, raw_input().split()))

    messages = [0 for i in xrange(n)]

    for i in xrange(k):
        x,y = map(int, raw_input().split())
        for r in xrange(n):
            messages[r] += a[r][y-1]
        messages[x-1] -= 1

    for m in messages: print m,

if __name__ == "__main__":
    main()


#Author: squiggly_lines
#Date: 31/05/2014
#Problem: 413B
from collections import defaultdict
def main():
    n,m,k = map(int, raw_input().split())

    a = []
    chat = defaultdict(set)
    for i in xrange(n):
        t = map(int, raw_input().split())
        for j in xrange(m):
            if t[j] == 1:
                chat[j+1].add(i+1)

    messages = defaultdict(lambda: 0)

    for i in xrange(k):
        x,y = map(int, raw_input().split())
        for member in chat[y]:
            if not member == x:
                messages[member] += 1

    for i in xrange(1,n+1):
        print messages[i],

if __name__ == "__main__":
    main();


'''
Created on Apr 20, 2014

@author: szalivako
'''

n, m, k = map(int, raw_input().split())

chats = [0 for i in range(m)]

a = [[] for i in range(n)]
for i in range(n):
    a[i] = map(int, raw_input().split())
    for j in range(m):
        chats[j] += a[i][j]

#print chats

members = [0 for i in range(n)]
messages = [0 for i in range(m)]

for i in range(k):
    x, y = map(int, raw_input().split())
    messages[y - 1] += 1
    members[x - 1] -= 1

#print messages

for i in range(m):
    for j in range(n):
        if (a[j][i] == 1):
            members[j] += messages[i]

ans = ''
for mi in members:
    ans += str(mi) + ' '
print ans


"""
http://codeforces.com/contest/413/problem/B
"""
N,M,K = map(int,raw_input().split())
A = [0]*N
ans = [0]*N
groupMsgs = [0]*M
for i in xrange(N) :
	A[i] = map(int,raw_input().split())
#print A
trans = zip(*A)
for index in xrange(M) :
	trans[index] = [i[0] for i in enumerate(trans[index]) if i[1] ==1 ]
trans = [0] + trans
#print trans[1:]
for _ in xrange(K) :
	sender, group = map(int,raw_input().split())
	groupMsgs[group-1]+=1
	#print "sender,group,groupMsgs = ",sender,group,groupMsgs
	ans[sender-1]-=1
	#print ans
for groupNo in xrange(1,M+1) :
	for i in trans[groupNo] :
		ans[i]+=groupMsgs[groupNo-1]
print " ".join(map(str,ans))


"""
http://codeforces.com/contest/413/problem/B
"""
N,M,K = map(int,raw_input().split())
A = [0]*N
ans = [0]*N
for i in xrange(N) :
	A[i] = map(int,raw_input().split())
#print A
trans = zip(*A)
for index in xrange(M) :
	trans[index] = [i[0] for i in enumerate(trans[index]) if i[1] ==1 ]
trans = [0] + trans
#print trans[1:]
for _ in xrange(K) :
	sender, group = map(int,raw_input().split())
	#print "sender,group = ",sender,group
	for i in trans[group] :
		ans[i]+=1
	ans[sender-1]-=1
	#print ans
print " ".join(map(str,ans))


#include <stdio.h>

#define N 20000
#define M 10

int main() {
	static int aa[N][M], xx[N], yy[M];
	int n, m, k, i, j;

	scanf("%d%d%d", &n, &m, &k);
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			scanf("%d", &aa[i][j]);
	while (k--) {
		scanf("%d%d", &i, &j), i--, j--;
		xx[i]++;
		yy[j]++;
	}
	for (i = 0; i < n; i++) {
		int y;

		y = 0;
		for (j = 0; j < m; j++)
			if (aa[i][j] == 1)
				y += yy[j];
		printf("%d ", y - xx[i]);
	}
	printf("\n");
	return 0;
}


#include <stdio.h>

#define N 20000
#define M 10

int main() {
	static int aa[N][M], kk[N];
	int n, m, k, i, j;

	scanf("%d%d%d", &n, &m, &k);
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			scanf("%d", &aa[i][j]);
	while (k--) {
		int x, y;

		scanf("%d%d", &x, &y), x--, y--;
		for (i = 0; i < n; i++)
			if (i != x && aa[i][y] == 1)
				kk[i]++;
	}
	for (i = 0; i < n; i++)
		printf("%d ", kk[i]);
	printf("\n");
	return 0;
}


/* https://codeforces.com/contest/413/submission/26347056 (rainboy) */
#include <stdio.h>

#define N 20000
#define M 10

int main() {
	static int aa[N][M], xx[N], yy[M];
	int n, m, k, i, j;

	scanf("%d%d%d", &n, &m, &k);
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			scanf("%d", &aa[i][j]);
	while (k--) {
		scanf("%d%d", &i, &j), i--, j--;
		xx[i]++;
		yy[j]++;
	}
	for (i = 0; i < n; i++) {
		int y;

		y = 0;
		for (j = 0; j < m; j++)
			if (aa[i][j] == 1)
				y += yy[j];
		printf("%d ", y - xx[i]);
	}
	printf("\n");
	return 0;
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
using System.Linq;

class TEST{
	static void Main(){
		Sol mySol=new Sol();
		mySol.Solve();
	}
}

class Sol{
	public void Solve(){
		int[] Table=new int[n];
		for(int i=0;i<n;i++)Table[i]=0;
		for(int i=0;i<n;i++){
			var d=Array.ConvertAll(Console.ReadLine().Split(' '),e=>int.Parse(e));
			for(int j=0;j<m;j++)Table[i]=Table[i]|(d[j]<<j);
		}
		int[][] Data=new int[m][];
		for(int i=0;i<m;i++){
			Data[i]=new int[n+1];
			for(int j=0;j<=n;j++)Data[i][j]=0;
		}

		for(int i=0;i<k;i++){
			var d=Array.ConvertAll(Console.ReadLine().Split(' '),e=>int.Parse(e));
			Data[d[1]-1][d[0]-1]++;
			Data[d[1]-1][n]++;
		}

		for(int i=0;i<n;i++){
			int ans=0;
			for(int j=0;j<m;j++){
				if((Table[i]&(0x1<<j))!=0){
					ans+=Data[j][n]-Data[j][i];
				}
			}
			if(i==0)Console.Write("{0}",ans);
			if(i>0)Console.Write(" {0}",ans);
		}
		Console.WriteLine("");
	}

	int n;
	int m;
	int k;

	public Sol(){
		var d=Array.ConvertAll(Console.ReadLine().Split(' '),e=>int.Parse(e));
		n=d[0];m=d[1];k=d[2];
	}
}


package main

import (
  "os"
  "bufio"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n, m, k := getI(), getI(), getI()
  channels := make([][]int, m+1)
  for c := 1; c <= m; c++ {
    channels[c] = []int{}
  }
  for u := 1; u <= n; u++ {
    for c := 1; c <= m; c++ {
      if getI() == 1 {
        channels[c] = append(channels[c], u)
      }
    }
  }

  userCounts := make([]int, n+1)
  channelCounts := make([]int, m+1)
  for i := 0; i < k; i++ {
    u, c := getI(), getI()
    userCounts[u]--
    channelCounts[c]++
  }
  for c := 1; c <= m; c++ {
    delta := channelCounts[c]
    for _, u := range channels[c] {
      userCounts[u] += delta
    }
  }
  writer.WriteString(fmt.Sprintf("%d", userCounts[1]))
  for u := 2; u <= n; u++ {
    writer.WriteString(fmt.Sprintf(" %d", userCounts[u]))
  }
  writer.WriteString("\n")
}


<?php

list($emps, $chats, $events) = explode(" ", trim(fgets(STDIN)));

$cc = array();

// don't do anything yet...
for($i = 1; $i <= $emps; $i++)
{
	$cc[$i] = explode(" ", trim(fgets(STDIN)));
}

$ce = array();
$cn = array_fill(1, $chats, 0);
$en = array_fill(1, $emps, 0);
for($i = 0; $i < $events; $i++)
{
	list($se, $re) = explode(" ", trim(fgets(STDIN)));
	$en[$se]--;
	$cn[$re]++;
}

for($i = 1; $i <= $emps; $i++)
{
	for($j = 0; $j < $chats; $j++)
	{
		$en[$i] += ($cc[$i][$j] == '1') * $cn[($j + 1)];
	}
}

echo implode(" ", $en) . PHP_EOL;


from collections import defaultdict
import math
n,m,k=map(int,input().split())
mat=[]
for _ in range(n):
    mat.append(list(map(int,input().split())))
values=[0]*10
sendby=defaultdict(lambda:0)
for _ in range(k):
    x,y=map(int,input().split())
    values[y-1]+=1
    sendby[x-1]+=1
for i in range(n):
    temp=0
    for j in range(m):
        if(mat[i][j]==1):
            temp+=values[j]
    print(temp-sendby[i],end=" ")


from collections import defaultdict
from sys import stdin, stdout
import math
n,m,k=map(int,stdin.readline().split())
mat=[]
for _ in range(n):
    mat.append(list(map(int,stdin.readline().split())))
values=[0]*10
sendby=defaultdict(lambda:0)
for _ in range(k):
    x,y=map(int,stdin.readline().split())
    values[y-1]+=1
    sendby[x-1]+=1
for i in range(n):
    temp=0
    for j in range(m):
        if(mat[i][j]==1):
            temp+=values[j]
    print(temp-sendby[i],end=" ")


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[]

for i in range(n):
    l.append(list(map(int,input().split())))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    e[t0-1]-=1
    c[t1-1]+=1

p=""

for i in range(n):
    for j in range(m):
        e[i]=e[i]+c[j]*l[i][j]
    p=p+str(e[i])+" "

print(p)


from sys import stdin,stdout

n,m,k=map(int,input().split())
l=[[0]*m]*n

for i in range(n):
    l[i]=list(map(int,stdin.readline().split()))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,stdin.readline().split())
    e[t0-1]-=1
    c[t1-1]+=1

p=[""]*n
for i in range(n):
    for j in range(m):
        e[i]=e[i]+c[j]*l[i][j]
    p[i]=str(e[i])

stdout.write(" ".join(p))


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[]

for i in range(n):
    l.append(list(map(int,input().split())))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    t[0][0]=t0
    t[0][1]=t1
    e[t0-1]-=1
    c[t0-1]+=1

p=""

for i in range(n):
    for j in range(m):
        if(l[i][j]):
            e[i]=e[i]+c[j]
    if(e[i]<0):
        p=p+"0 "
    else:
        p=p+str(e[i])+" "

print(p)


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[]

for i in range(n):
    l.append(list(map(int,input().split())))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    t[0][0]=t0
    t[0][1]=t1
    e[t0-1]-=1
    c[t1-1]+=1

p=""

for i in range(n):
    for j in range(m):
        e[i]=e[i]+c[j]*l[i][j]
    p=p+str(e[i])+" "

print(p)


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[]

for i in range(n):
    l.append(input().split())
    for j in range(m):
        l[i][j]=int(l[i][j])

t=[]
r,c=n,m
e=[0 for x in range(r)]
c=[0 for x in range(m)]

for i in range(k):
    t.append(input().split())
    t[i][0]=int(t[i][0])
    e[t[i][0]-1]=e[t[i][0]-1]-1
    t[i][1]=int(t[i][1])
    c[t[i][1]-1]=c[t[i][1]-1]+1

p=""

for i in range(n):
    for j in range(m):
        if(l[i][j]):
            e[i]=e[i]+c[j]
    p=p+str(e[i])+" "

print(p)


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[[0]*m]*n

for i in range(n):
    l[i]=list(map(int,input().split()))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    e[t0-1]-=1
    c[t1-1]+=1

p=""
for i in range(n):
    for j in range(m):
        e[i]=e[i]+c[j]*l[i][j]
    p=p+str(e[i])+" "

print(p)


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[[0]*m]*n

for i in range(n):
    l[i]=list(map(int,input().split()))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    e[t0-1]-=1
    c[t1-1]+=1

p=[""]*n
for i in range(n):
    for j in range(m):
        e[i]=e[i]+c[j]*l[i][j]
    p[i]=str(e[i])

print(" ".join(p))


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[]

for i in range(n):
    l.append(list(map(int,input().split())))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    t[0][0]=t0
    t[0][1]=t1
    e[t0-1]-=1
    c[t1-1]+=1

p=""

for i in range(n):
    for j in range(m):
        if(l[i][j]):
            e[i]=e[i]+c[j]
    if(e[i]<0):
        p=p+"0 "
    else:
        p=p+str(e[i])+" "

print(p)


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[]

for i in range(n):
    l.append(list(map(int,input().split())))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    t[0][0]=t0
    t[0][1]=t1
    e[t0-1]-=1
    c[t0-1]+=1

p=""

for i in range(n):
    for j in range(m):
        if(l[i][j]):
            e[i]=e[i]+c[j]
    p=p+str(e[i])+" "

print(p)


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[]

for i in range(n):
    l.append(list(map(int,input().split())))

t=[(0,0)]*k
r,c=n,m
e=[0 for x in range(r)]
c=[0 for x in range(m)]

for i in range(k):
    t0,t1=map(int,input().split())
    t[0][0],t[0][1]=t0,t1
    e[t0-1]-=1
    c[t0-1]+=1

p=""

for i in range(n):
    for j in range(m):
        if(l[i][j]):
            e[i]=e[i]+c[j]
    p=p+str(e[i])+" "

print(p)


n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
l=[[0]*n]*m

for i in range(n):
    l[i]=list(map(int,input().split()))

t=[[0]*2]*k
e=[0]*n
c=[0]*m

for i in range(k):
    t0,t1=map(int,input().split())
    e[t0-1]-=1
    c[t1-1]+=1

p=""
for i in range(n):
    for j in range(m):
        e[i]=e[i]+c[j]*l[i][j]
    p=p+str(e[i])+" "

print(p)


from sys import stdin,stdout
a,b,c=map(int,stdin.readline().split())
z=[list(map(int,stdin.readline().split())) for _ in " "*a]
k=[0]*a
m=[0]*b;ans=[0]*a
for _ in " "*c:
    u,v=map(int,stdin.readline().split())
    k[u-1]+=1;m[v-1]+=1
for i in range(a):
    ans[i]=-k[i]
    for j in range(b):ans[i]+=m[j]*z[i][j]
stdout.write(' '.join(map(str,ans)))


n=int(input())
a=list(input())
it=list(map(int,input().split()))
for i in range(len(a)):
    c=int(a[i])
    if it[c-1]>c:
        k=i
        while a[k]==str(c):
            a[k]=str(it[c-1])
            k+=1
            if k==n:
                break
        break
print(''.join(a))


n=int(input())
a=list(input())
it=list(map(int,input().split()))
for i in range(len(a)):
    try:
        if i<p:
            continue
    except:
        pass
    c=int(a[i])
    try:
        if i-z>1:
            break
    except:
        pass
    if it[c-1]>c:
        k=i
        z=i
        while a[k]==str(c):
            a[k]=str(it[c-1])
            k+=1
            p=k
            if k==n:
                break
print(''.join(a))


n=int(input())
a=list(input())
it=list(map(int,input().split()))
import sys
ok=0
for i in range(len(a)):
    ch=int(a[i])
    zam=it[ch-1]
    p=i
    b=0
    while (zam>=ch and b>0) or (zam>ch and b==0):
        ok=1
        while a[p]==str(ch):
            a[p]=str(zam)
            p+=1
            b+=1
            if p==n:
                print(''.join(a))
                sys.exit()
        ch=int(a[p])
        zam=it[ch-1]
    if ok==1:
        print(''.join(a))
        sys.exit()
print(''.join(a))


n=int(input())
a=list(input())
it=list(map(int,input().split()))
import sys
ok=0
for i in range(len(a)):
    ch=int(a[i])
    zam=it[ch-1]
    p=i
    while zam>ch:
        ok=1
        while a[p]==str(ch):
            a[p]=str(zam)
            p+=1
            if p==n:
                print(''.join(a))
                sys.exit()
        ch=int(a[p])
        zam=it[ch-1]
    if ok==1:
        print(''.join(a))
        sys.exit()
print(''.join(a))


n=int(input())
a=list(input())
it=list(map(int,input().split()))
for i in range(len(a)):
    c=int(a[i])
    try:
        if i-z>1:
            break
    except:
        if it[c-1]>c:
            k=i
            z=i
            while a[k]==str(c):
                a[k]=str(it[c-1])
                k+=1
                if k==n:
                    break
print(''.join(a))


n=int(input())
a=list(input())
it=list(map(int,input().split()))
for i in range(len(a)):
    c=int(a[i])
    try:
        if i-z>1:
            break
    except:
        pass
    if it[c-1]>c:
        k=i
        z=i
        while a[k]==str(c):
            a[k]=str(it[c-1])
            k+=1
            if k==n:
                break
print(''.join(a))


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive

ans = ""
for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if ic < maps_to:

        start_index = True
        ans += str(maps_to)
        continue
    elif ic > maps_to:
        if start_index is not None:
            end_index = True
    ans += c

print(ans)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive

for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if ic < maps_to:
        if start_index is None:
            start_index = i
    elif ic > maps_to:
        if start_index is not None:
            end_index = i

if alen == 200000:
    print("done")

if start_index is not None:
    for i in range(start_index, end_index if end_index else len(a)):
        a = a[:i] + funcs[int(a[i])-1] + a[1+i:]

print(a)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive

for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if ic < maps_to:
        if start_index is None:
            start_index = i
    elif ic > maps_to:
        if start_index is not None:
            end_index = i

if start_index:
    for i in range(start_index, end_index if end_index else len(a)):
        a = a[:i] + funcs[int(a[i])-1] + a[1+i:]

print(a)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive
if alen == 200000:
    print(funcs)
ans = ""
for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if ic < maps_to:

        start_index = True
        ans += str(maps_to)
        continue
    elif ic > maps_to:
        if start_index is not None:
            end_index = True
    ans += c

print(ans)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive

for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if ic < maps_to:
        if start_index is None:
            start_index = i
    elif ic > maps_to:
        if start_index is not None:
            end_index = i

if start_index is not None:
    for i in range(start_index, end_index if end_index else len(a)):
        a = a[:i] + funcs[int(a[i])-1] + a[1+i:]

print(a)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive
if alen == 200000:
    print(funcs)
ans = ""
for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if not end_index:
        if ic < maps_to:

            start_index = True
            ans += str(maps_to)
            continue
        elif ic > maps_to:
            if start_index is not None:
                end_index = True
    ans += c

print(ans)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive

for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if ic < maps_to:
        if start_index is None:
            start_index = i
    elif ic > maps_to:
        if start_index is not None:
            end_index = i

for i in range(start_index, end_index):
    a = a[:i] + funcs[int(a[i])-1] + a[1+i:]

print(a)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive
ans = ""
for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if not end_index:
        if ic < maps_to:

            start_index = True
            ans += str(maps_to)
            continue
        elif ic > maps_to:
            if start_index is not None:
                end_index = True
    ans += c

print(ans)


alen = int(input())
a = input()
funcs = input().split()

# The idea would be to pick the starting number, and then pick the ending number
# 1 3 3 7
# 1 2 5 4 6 6 3 1 9
#
# Go through each character in a
# 1
# 1 maps to 1
# If it's the equivalent number, continue
# If it maps into a lower number, continue
# (continue
# 3 maps to 5
# Now we have our starting number
# 3 maps to 5 again
# Add this to the contiguous sequence
# 7 maps to 3
# We stop since it maps to a number less than itself
# Do not add this to contiguous sequence
# Apply f to numbers [1-3)

start_index = None  # Inclusive
end_index = None    # Exclusive

for i, c in enumerate(a):
    ic = int(c)
    maps_to = int(funcs[ic-1])
    if ic < maps_to:
        if start_index is None:
            start_index = i
    elif ic > maps_to:
        if start_index is not None:
            end_index = i

if start_index is not None:
    for i in range(start_index, end_index if end_index else len(a)):
        a = a[:i] + funcs[int(a[i])-1] + a[1+i:]

if alen == 200000:
    print("done")
print(a)


n = int(input())
d = [x for x in str(input())]

f = [0] + [int(x) for x in input().split(' ')]

res = []

for e in d:
    e = int(e)
    if f[e] > e:
        res.append(f[e])
    else:
        res.append(e)

print("".join([str(x) for x in res]))


n = int(input())
d = [x for x in str(input())]

f = [0] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if f[e+1] >= e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


n = int(input())
d = [x for x in input().strip()]

f = [-1] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if f[e] > e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


n = int(input())
d = [x for x in input().strip()]

f = [0] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if f[e] > e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


n = int(input())
d = [x for x in str(input())]

f = [0] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if f[e] >= e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <memory>
#include <cctype>
#include <cstring>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <iomanip>

using namespace std;

typedef long long ll;
typedef long double ld;

#define PB push_back
#define MP make_pair
#define EPS 1e-5
#define FOR(i, a, b) for(i = (a); i < (b); ++i)
#define RFOR(i, a, b) for(i = (a) - 1; i >= (b); --i)
#define sqr(a) ((a)*(a))

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int n ;
    cin >> n;
    //cout << n;
    string a;
    cin >> a;
    int d[n];
    int i;
    FOR(i, 0, n){
        d[i] = a[i];
        cout << d[i] << ' ';
    }
    char f[9];
    FOR(i, 0, 9){
        cin >> f[i];
        //cout << f[i] << ' ';
    }
    char res[n];
    FOR(i, 0, n){
        if(f[d[i] - 48] > a[i - 48]){
            res[i] = f[d[i] - 48] ;
        }
        else{
            res[i] = d[i];
        }
    }
    FOR(i, 0, n){
        cout << (res[i]);
    }
    return 0;
}


n = int(input())
d = [x for x in input().strip()]

f = [-1] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if not b:
        if f[e] > e:
            d[i] = f[e]
            b = True
    if f[e] >= e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


n = int(input())
d = [x for x in input().strip()]

f = [-1] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if not b:
        if f[e] > e:
            d[i] = f[e]
            b = True
    elif f[e] >= e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


n = int(input())
d = [x for x in input().strip()]

f = [-1] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if f[e] >= e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


n = int(input())
d = [x for x in str(input())]

f = [0] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if f[e] >= e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

if not b:
    d[-1] = f[int(d[-1])]

print("".join([str(x) for x in d]))


n = int(input())
d = [x for x in str(input())]

f = [0] + [int(x) for x in input().split(' ')]

b = False
for i, e in enumerate(d):
    e = int(e)
    if f[e] > e:
        d[i] = f[e]
        b = True
    else:
        if b:
            break

print("".join([str(x) for x in d]))


n=input()
s=input()
d=list(map(int,input().split()))
c=""
for i in s:
    c+=str(max(int(i),d[int(i)-1]))
print(c)


n=input()
s=input()
d=list(map(str,input().split()))
e=[i for i in range(1,10)]
for i in e:
    p=[i,int(d[i-1])]
    e[i-1]=max(p)
c=""
r=0
for i in s:
    if r==0:
        if int(i)<e[int(i)-1]:
            c+=str(e[int(i)-1])
            r+=1
        else:
            c+=i
    elif r==1:
        if int(i)>e[int(i)-1]:
            print(int(i),e[int(i)-1])
            c+=i
            r+=1
        else:
            c+=str(e[int(i)-1])
    else:
        c+=i
print(c)


n=input()
s=input()
d=list(map(int,input().split()))
r=0
c=""
for i in s:
    if r==0:
        if int(i)<d[int(i)-1]:
            c+=str(d[int(i)-1])
            r=1
        else:
            c+=i
    elif r==1:
        if int(i)>d[int(i)-1]:
            c+=i
            r=2
        else:
            c+=str(d[int(i)-1])
    else:
        c+=i
print(c)


n=input()
s=input()
d=list(map(str,input().split()))
e=[i for i in range(1,10)]
for i in e:
    p=[i,int(d[i-1])]
    e[i-1]=str(max(p))
c=""
for i in s:
    c+=e[int(i)-1]
print(c)


n=input()
s=input()
d=list(map(str,input().split()))
e=[i for i in range(1,10)]
for i in e:
    p=[i,int(d[i-1])]
    e[i-1]=max(p)
c=""
r=0
for i in s:
    if r==0:
        if int(i)<e[int(i)-1]:
            c+=str(e[int(i)-1])
            r+=1
        else:
            c+=i
    elif r==1:
        if int(i)>e[int(i)-1]:
            c+=i
            r+=1
        else:
            c+=str(e[int(i)-1])
    else:
        c+=i
print(c)


import math
T=int(input())
a=str(input())
f=list(map(int,input().split()))
d=[]
for i in range(T):
    k=int(a[i])
    if(f[k-1]>k):
        d.append(f[k-1])
    else:
        d.append(k)
for i in d:
    print(i,end="")


import math
T=int(input())
a=str(input())
f=list(map(int,input().split()))
d=[]
flag=0
for i in range(T):
    k=int(a[i])
    if(f[k-1]>=k and flag<2):
        d.append(f[k-1])
        flag=1
    else:
        if(flag==1):
            flag=2
        d.append(k)
for i in d:
    print(i,end="")


import math
T=int(input())
a=str(input())
f=list(map(int,input().split()))
d=[]
flag=0
for i in range(T):
    k=int(a[i])
    if(f[k-1]>k and flag<2):
        d.append(f[k-1])
        flag=1
    else:
        if(flag==1):
            flag=2
        d.append(k)
for i in d:
    print(i,end="")


import math
T=int(input())
a=str(input())
f=list(map(int,input().split()))
d=[]
flag=0
for i in range(T):
    k=int(a[i])
    if(f[k-1]>k and flag<2):
        d.append(f[k-1])
        flag=1
    elif(f[k-1]==k):
        d.append(f[k-1])
    else:
        if(flag==1):
            flag=2
        d.append(k)
for i in d:
    print(i,end="")


n=int(input())
t=str(input())
f=str(input()).split(" ")
s=[]
c=[]
p=""
for i in t:
    s.append(int(i))
for i in range(n):
    c.append(-(s[i]-int(f[s[i]-1])))
t=-1
for i in range(n):
    if c[i]>0:
        break
t=i
if t==-1:
    for i in s:
        p=p+str(i)
    print(p)
else:
    q=n
    for i in range(t,n):
        if c[i]<0:
            q==i
            break
    for i in range(t,q):
        s[i]=int(f[int(s[i]-1)])
    for i in s:
        p=p+str(i)
    print(p)


n=int(input())
d=str(input())
s=[]
for i in range(n):
    s.append(d[i])
f=str(input()).split(" ")
for i in range(9):
    f[i]=int(f[i])
for i in range(n):
    s[i]=int(s[i])
m=0
q=0
w=n
for i in range(0,n):
    for j in range(0,n):
        c=0
        for p in range(i,j+1):
            c=c+f[s[p]-1]-s[p]
        if c>m:
            m=c
            q=i
            w=j
for i in range(q,w+1):
    s[i]=f[s[i]-1]
y=""
for i in range(n):
    y=y+str(s[i])
print(y)


n=int(input())
t=str(input())
f=str(input()).split(" ")
s=[]
c=[]
p=""
for i in t:
    s.append(int(i))
for i in range(n):
    c.append(-(s[i]-int(f[s[i]-1])))
t=-1
for i in range(n):
    if c[i]>0:
        break
t=i
if t==-1:
    for i in s:
        p=p+str(i)
    print(p)
else:
    q=n
    for i in range(t,n):
        if c[i]<0:
            break
    q=i
    for i in range(t,q):
        s[i]=int(f[int(s[i]-1)])
    for i in s:
        p=p+str(i)
    print(p)


n=int(input())
d=str(input())
s=[]
for i in range(n):
    s.append(d[i])
f=str(input()).split(" ")
for i in range(9):
    f[i]=int(f[i])
for i in range(n):
    s[i]=int(s[i])
m=0
q=0
w=n
for i in range(0,n):
    for j in range(0,n):
        c=0
        for p in range(i,j):
            c=c+f[s[p]-1]-s[p]
        if c>m:
            m=c
            q=i
            w=j
for i in range(q,w):
    s[i]=f[s[i]-1]
y=""
for i in range(n):
    y=y+str(s[i])
print(y)


n=int(input())
d=str(input())
s=[]
for i in range(n):
    s.append(d[i])
f=str(input()).split(" ")
for i in range(9):
    f[i]=int(f[i])
for i in range(n):
    s[i]=int(s[i])
m=0
q=0
w=0
for i in range(0,n):
    for j in range(i,n):
        c=0
        for p in range(i,j+1):
            c=c+f[s[p]-1]-s[p]
        if c>m:
            m=c
            q=i
            w=j+1
for i in range(q,w):
    s[i]=f[s[i]-1]
y=""
for i in range(n):
    y=y+str(s[i])
print(y)


n=int(input())
t=str(input())
f=str(input()).split(" ")
s=[]
c=[]
p=""
for i in t:
    s.append(int(i))
for i in range(n):
    c.append(-(s[i]-int(f[s[i]-1])))
t=-1
for i in range(n):
    if c[i]>0:
        break
t=i
if t==-1:
    for i in s:
        p=p+str(i)
    print(p)
else:
    q=n
    b=True
    for i in range(t,n):
        if c[i]<0:
            b=False
            break
    if b==False:
        q=i
    for i in range(t,q):
        s[i]=int(f[int(s[i]-1)])
    for i in s:
        p=p+str(i)
    print(p)


n=int(input())
d=str(input())
s=[]
for i in range(n):
    s.append(d[i])
f=str(input()).split(" ")
for i in range(9):
    f[i]=int(f[i])
for i in range(n):
    s[i]=int(s[i])
m=0
q=0
w=n
for i in range(0,n):
    for j in range(0,n):
        c=0
        for p in range(i,j):
            c=c+f[s[p]-1]-s[p]
        if c>m:
            m=c
            q=i
            w=j
for i in range(q,w+1):
    s[i]=f[s[i]-1]
y=""
for i in range(n):
    y=y+str(s[i])
print(y)


n = int(input())
s = input()
a = []
for el in s:
	a.append(el)
arr = list(map(str, input().split()))
max_ = 0
for i in range(0, n):
	for j in range(i, n):
		test = a.copy()
		for k in range(i, j + 1):
			test[k] = arr[int(test[k]) - 1]
		w = ''
		for el in test:
			w += el
		if int(w) > max_:
			max_ = int(w)
print(max_)


n = int(input())
s = input()
a = []
for el in s:
	a.append(el)
arr = list(map(int, input().split()))
max_ = a
for i in range(n):
	if arr[int(s[i]) - 1] > int(s[i]):
		test = a.copy()
		test[i] = arr[int(s[i]) - 1]
		for j in range(i, n):
			if arr[int(s[j]) - 1] <= int(s[j]):
				break
			test[j] = arr[int(s[j]) - 1]
		max_ = test.copy()
		break

for el in max_:
	print(el, end = "")


n = int(input())
s = input()
a = []
for el in s:
	a.append(el)
arr = list(map(int, input().split()))
max_ = a
for i in range(n):
	if arr[int(s[i]) - 1] > int(s[i]):
		test = a.copy()
		test[i] = arr[int(s[i]) - 1]
		for j in range(i, n):
			if arr[int(s[j]) - 1] <= int(s[j]):
				break
			test[j] = arr[int(s[j]) - 1]
		max_ = test
		break

for el in max_:
	print(el, end = "")


n = int(input())
s = input()
k = int(s)
a = []
for el in s:
	a.append(el)
arr = list(map(int, input().split()))
max_ = a
for i in range(n):
	if arr[int(s[i]) - 1] > int(s[i]):
		test = a.copy()
		test[i] = arr[int(s[i]) - 1]
		go = 1
		for j in range(i, n):
			if arr[int(s[j]) - 1] <= int(s[j]):
				go = 0
			if go == 1:
				test[j] = arr[int(s[j]) - 1]
		summ = 0
		for l in range(len(test)):
			summ += int(test[l]) * (10 ** (len(test) - l - 1))
		if summ > k:
			max_ = test.copy()
		break

for el in max_:
	print(el, end = "")


n = int(input())
s = input()
k = int(s)
a = []
for el in s:
	a.append(el)
arr = list(map(int, input().split()))
max_ = a
for i in range(n):
	if arr[int(s[i]) - 1] > int(s[i]):
		test = a.copy()
		test[i] = arr[int(s[i]) - 1]
		go = 1
		for j in range(i + 1, n):
			if arr[int(s[j]) - 1] < int(s[j]):
				go = 0
			if go == 1:
				test[j] = arr[int(s[j]) - 1]
		max_ = test.copy()
		break

for el in max_:
	print(el, end = "")


n = int(input())
s = input()
a = []
for el in s:
	a.append(el)
arr = list(map(str, input().split()))
max_ = 0
for i in range(n):
	for j in range(i, n + 1):
		#print(i, j)
		test = a.copy()
		for k in range(i, j):
			test[k] = arr[int(test[k]) - 1]
		w = ''
		for el in test:
			w += el
		#print(w)
		if int(w) > max_:
			max_ = int(w)
print(max_)


n = int(input())
s = input()
a = []
for el in s:
	a.append(el)
arr = list(map(int, input().split()))
max_ = a
for i in range(n):
	if arr[int(s[i]) - 1] > int(s[i]):
		test = a.copy()
		test[i] = arr[int(s[i]) - 1]
		go = 1
		for j in range(i, n):
			if arr[int(s[j]) - 1] <= int(s[j]):
				go = 0
			if go == 1:
				test[j] = arr[int(s[j]) - 1]
		max_ = test.copy()
		break

for el in max_:
	print(el, end = "")


import sys
if len(sys.argv) >= 2:
    if sys.argv[1] == "LOCAL":
        sys.stdin = open("input.in", 'r')

n = int(input())

s = input()

l = [int(i) for i in input().split()]
i = 0
a = 0
while i < n:
    index = int(s[i])
    if (l[index - 1] > index and a >= 0):
        print(l[index - 1], end="")
        a += 1
    else :
        print(s[i], end="")
        if a > 0:
            a = -1
    i += 1


import sys
if len(sys.argv) >= 2:
    if sys.argv[1] == "LOCAL":
        sys.stdin = open("input.in", 'r')

n = int(input())

s = input()

l = [int(i) for i in input().split()]
i = 0
a = True
while i < n:
    index = int(s[i])
    if (l[index - 1] > index and a):
        print(l[index - 1], end="")
    else:
        print(s[i], end="")
        a = False
    i += 1


import sys
if len(sys.argv) >= 2:
    if sys.argv[1] == "LOCAL":
        sys.stdin = open("input.in", 'r')

n = int(input())

s = input()

l = [int(i) for i in input().split()]
i = 0
while i < n:
    index = int(s[i])
    if l[index - 1] > index:
        break
    print(s[i], end="")
    i += 1
while i < n:
    index = int(s[i])
    if l[index - 1] >= index:
        print(l[index - 1], end="")
    else:
        break
    i += 1
while i < n:
    print(s[i], end="")
    i += 1


import sys
if len(sys.argv) >= 2:
    if sys.argv[1] == "LOCAL":
        sys.stdin = open("input.in", 'r')

n = int(input())

s = input()

l = [int(i) for i in input().split()]

for i in s:
    index = int(i)
    if (l[index - 1] > index):
        print(l[index - 1], end="")
    else:
        print(index, end="")


import sys
if len(sys.argv) >= 2:
    if sys.argv[1] == "LOCAL":
        sys.stdin = open("input.in", 'r')

n = int(input())

s = input()

l = [int(i) for i in input().split()]
i = 0
while i < n:
    index = int(s[i])
    if (l[index - 1] > index):
        print(l[index - 1], end="")
    else:
        print(s[i], end="")
    i += 1


# https://codeforces.com/problemset/problem/1157/B

digits = int(input())
number = str(input())
functions = input().split()

max_result = ''
started = 0
stopped = 0

for i in range(digits):
    if started == 0 and stopped == 0:
        if int(functions[int(number[i]) - 1]) > int(number[i]):
            max_result += (functions[int(number[i]) - 1])
            started = 1
        else:
            max_result += number[i]
    elif started == 1 and stopped == 0:
        if int(functions[int(number[i]) - 1]) >= int(number[i]):
            max_result += (functions[int(number[i]) - 1])
        else:
            max_result += number[i]
            stopped = 1
    else:
        max_result += number[i]

print(int(max_result))


# https://codeforces.com/problemset/problem/1157/B

digits = int(input())
number = str(input())
functions = input().split()

max_result = ''
started = 0
stopped = 0
endpoint = len(number) - 1

for i in range(digits):
    if started == 0 and stopped == 0:
        if int(functions[int(number[i]) - 1]) > int(number[i]):
            max_result += (functions[int(number[i]) - 1])
            started = 1
        else:
            max_result += number[i]
    elif started == 1 and stopped == 0:
        if int(functions[int(number[i]) - 1]) >= int(number[i]):
            max_result += (functions[int(number[i]) - 1])
        else:
            max_result += number[i]
            endpoint = i
            break

if endpoint < len(number) - 1:
    max_result += number[endpoint + 1:]

print(int(max_result))


# https://codeforces.com/problemset/problem/1157/B

digits = int(input())
number = list(map(int,input()))
functions = list(map(int, input().split()))

functions = [0] + functions

for i in range(digits):
    if functions[number[i]] > number[i]:
        while i < digits and functions[number[i]] >= number[i]:
            number[i] = functions[number[i]]
            i += 1
        break

print(''.join(map(str, number)))


# https://codeforces.com/problemset/problem/1157/B

digits = int(input())
number = list(map(int,input()))
functions = list(map(int, input().split()))

functions = [0] + functions

for i in range(digits):
    if functions[number[i]] > number[i]:
        while i < digits and functions[number[i]] >= number[i]:
            number[i] = functions[number[i]]
            i += 1
        break

print(' '.join(map(str, number)))


# https://codeforces.com/problemset/problem/1157/B

digits = int(input())
number = str(input())
functions = input().split()

max_result = ''
started = 0
stopped = 0

for i in range(digits):
    if started == 0 and stopped == 0:
        if int(functions[int(number[i]) - 1]) > int(number[i]):
            max_result += (functions[int(number[i]) - 1])
            started = 1
        else:
            max_result += number[i]
    elif started == 1 and stopped == 0:
        if int(functions[int(number[i]) - 1]) >= int(number[i]):
            max_result += (functions[int(number[i]) - 1])
        else:
            max_result += number[i]
            endpoint = i
            break

max_result += number[endpoint + 1:]

print(int(max_result))


length = input()
digits = [int(i) for i in input()]
functions = list(map(int, input().split()))

active = 0
for i in range(len(digits)):
    d = digits[i]
    f = functions[d - 1]
    if d <= f:
        digits[i] = f
        active = 1
    else:
        if active == 1:
            break

print(''.join(map(str, digits)))


n = int(input())

a = input()
new = list(a)
s = set(a)
f = input().split()
d = {}
for i in range(1, 10):
    d[str(i)] = f[i-1]
flag = False
for i in range(n):
    if a[i] < d[a[i]]:
        new[i] = d[a[i]]
        flag = True
    elif flag == True:
        break
print("".join(new))


n = int(input())

a = list(input())
f = input().split()
d = {str(i+1): f[i] for i in range(9)}

flag = False

for i in range(n):
    if a[i] < d[a[i]]:
        a[i] = d[a[i]]
        flag = True
    elif a[i] > d[a[i]] and flag == True:
        break
print("".join(a))


n = int(input())

a = list(input())
f = input().split()
d = {str(i+1): f[i] for i in range(9)}

flag = False

for i in range(n):
    if a[i] <= d[a[i]]:
        a[i] = d[a[i]]
        flag = True
    elif flag == True:
        break
print("".join(a))


n = int(input())

a = input()
s = set(a)
f = input().split()
d = {}
for i in range(1, 10):
    d[str(i)] = f[i-1]
ma = int(a)
for i in s:
    temp = int(a.replace(str(i), d[i]))
    if temp > ma:
        ma = temp
print(ma)


n=int(input())
num=input()
mx=int(num)
val=dict()
vals=input().split()
for i in range(1,10):
    val[i]=int(vals[i-1])
flag=False
temp=num
c=0
ans=''
fill=False
for i in range(n):
    f=False
    if(int(temp[i])>val[int(temp[i])]):
        if flag:
            fill=True
        else:
            ans=ans+temp[i]
        f=True
    elif(int(temp[i])<val[int(temp[i])] and not(fill)):
        flag=True
        c=1
        f=True
        ans=ans+str(val[int(temp[i])])
        #temp=temp[0:i]+str(val[int(temp[i])])+temp[i+1:n]
    if(fill==True or f==False):
        ans=ans+temp[i]
if c==0:
    print(num)
else:
    print(ans)


n=int(input())
num=input()
mx=int(num)
val=dict()
vals=input().split()
for i in range(1,10):
    val[i]=int(vals[i-1])
flag=False
temp=num
for i in range(n):
    if(int(temp[i])>=val[int(temp[i])] and flag):
        break
    elif(int(temp[i])<val[int(temp[i])]):
        flag=True
        temp=temp[0:i]+str(val[int(temp[i])])+temp[i+1:n]
print(temp)


n=int(input())
num=input()
mx=int(num)
val=dict()
vals=input().split()
for i in range(1,10):
    val[i]=int(vals[i-1])
flag=False
temp=num
ans=''
c=0
for i in range(n):
    if(int(temp[i])<val[int(temp[i])]):
        flag=True
        ans=ans+str(val[int(temp[i])])
        c+=2
    else:
        ans+=temp[i]
if c==0:
    print(num)
else:
    print(ans)


n=int(input())
num=input()
mx=int(num)
val=dict()
vals=input().split()
for i in range(1,10):
    val[i]=int(vals[i-1])
flag=False
temp=num
for i in range(n):
    if(int(temp[i])>val[int(temp[i])] and flag):
        break
    elif(int(temp[i])<=val[int(temp[i])]):
        flag=True
        temp=temp[0:i]+str(val[int(temp[i])])+temp[i+1:n]
if mx>int(temp):
    print(num)
else:
    print(temp)


n=int(input())
num=input()
mx=int(num)
val=dict()
vals=input().split()
for i in range(1,10):
    val[i]=int(vals[i-1])
flag=False
temp=num
for i in range(n):
    if(int(temp[i])>val[int(temp[i])] and flag):
        break
    elif(int(temp[i])<val[int(temp[i])]):
        flag=True
        temp=temp[0:i]+str(val[int(temp[i])])+temp[i+1:n]
if mx>int(temp):
    print(num)
else:
    print(temp)


n=int(input())
num=input()
mx=int(num)
val=dict()
vals=input().split()
for i in range(1,10):
    val[i]=int(vals[i-1])
flag=False
temp=num
for i in range(n):
    if(int(temp[i])>val[int(temp[i])] and flag):
        break
    elif(int(temp[i])<=val[int(temp[i])]):
        flag=True
        temp=temp[0:i]+str(val[int(temp[i])])+temp[i+1:n]
print(temp)


def get():
    """prepare data from input"""
    n = int(input())
    a = input()
    keys = ('1', '2', '3', '4', '5',
            '6', '7', '8', '9')
    values = input().split()
    f = dict(zip(keys, values))
    return n, a, f

def first_greater(a, f):
    """
    return index of first greater
    digit or return last++ if there aren't such
    """
    for i, d in enumerate(a):
        if f[d] > d:
            return i
    else:
        return i

def main():
    n, a, f = get()
    fg = first_greater(a, f)
    bef = a[:fg]
    fgd = a[fg]
    mid = f[fgd]
    if fg+1 == len(a):
        aft = ''
    else:
        i = fg + 1
        d = a[i]
        while f[d] >= d or i < len(a)-1:
            mid += f[d]
            i+=1
            d = a[i]
        aft = a[i:]
    print(bef, mid, aft, sep='')

if __name__ == '__main__':
    main()


def get():
    """prepare data from input"""
    n = int(input())
    a = input()
    keys = ('1', '2', '3', '4', '5',
            '6', '7', '8', '9')
    values = input().split()
    f = dict(zip(keys, values))
    return n, a, f

def first_greater(a, f):
    """
    return index of first greater
    digit or return last++ if there aren't such
    """
    for i, d in enumerate(a):
        if f[d] > d:
            return i
    else:
        return i

def main():
    n, a, f = get()
    fg = first_greater(a, f)
    bef = a[:fg]
    fgd = a[fg]
    mid = f[fgd]
    aft = ''
    if fg+1 != len(a):
        for i, d in enumerate(a[fg+1:], start = fg+1):
            if f[d] >= d:
                mid+=f[d]
            else:
                aft = a[i:]
                break
    print(bef, mid, aft, sep='')

if __name__ == '__main__':
    main()


def get():
    """prepare data from input"""
    n = int(input())
    a = input()
    keys = ('1', '2', '3', '4', '5',
            '6', '7', '8', '9')
    values = input().split()
    f = dict(zip(keys, values))
    return n, a, f

def first_greater(a, f):
    """
    return index of first greater
    digit or return last++ if there aren't such
    """
    for i, d in enumerate(a):
        if f[d] > d:
            return i
    else:
        return i

def main():
    n, a, f = get()
    fg = first_greater(a, f)
    bef = a[:fg]
    fgd = a[fg]
    mid = f[fgd]
    aft = ''
    if fg+1 != len(a):
        for i, d in enumerate(a[fg+1:]):
            if f[d] >= d:
                mid+=f[d]
            else:
                aft = a[i:]
                break
    print(bef, mid, aft, sep='')

if __name__ == '__main__':
    main()


def get():
    """prepare data from input"""
    n = int(input())
    a = input()
    keys = ('1', '2', '3', '4', '5',
            '6', '7', '8', '9')
    values = input().split()
    f = dict(zip(keys, values))
    return n, a, f

def first_greater(a, f):
    """
    return index of first greater
    digit or return last++ if there aren't such
    """
    for i, d in enumerate(a):
        if f[d] > d:
            return i
    else:
        return i

def main():
    n, a, f = get()
    fg = first_greater(a, f)
    bef = a[:fg]
    fgd = a[fg]
    mid = f[fgd]
    if fg+1 == len(a):
        aft = ''
    else:
        i = fg + 1
        d = a[i]
        while f[d] >= d and i < len(a):
            mid += f[d]
            d = a[i]
            i+=1
        aft = a[i:]
    print(bef, mid, aft, sep='')

if __name__ == '__main__':
    main()


def get():
    """prepare data from input"""
    n = int(input())
    a = input()
    keys = ('1', '2', '3', '4', '5',
            '6', '7', '8', '9')
    values = input().split()
    f = dict(zip(keys, values))
    return n, a, f

def first_greater(a, f):
    """
    return index of first greater
    digit or return last++ if there aren't such
    """
    for i, d in enumerate(a):
        if f[d] > d:
            return i
    else:
        return i

def main():
    n, a, f = get()
    fg = first_greater(a, f)
    bef = a[:fg]
    fgd = a[fg]
    mid = f[fgd]
    if fg+1 == len(a):
        aft = ''
    else:
        i = fg+1
        d = a[i]
        while f[d] >= d:
            mid += f[d]
            i+=1
            d = a[i]
        aft = a[i:]
    print(bef, mid, aft, sep='')

if __name__ == '__main__':
    main()


def get():
    """prepare data from input"""
    n = int(input())
    a = input()
    keys = ('1', '2', '3', '4', '5',
            '6', '7', '8', '9')
    values = input().split()
    f = dict(zip(keys, values))
    return n, a, f

def first_greater(a, f):
    """
    return index of first greater
    digit or return last++ if there aren't such
    """
    for i, d in enumerate(a):
        if f[d] > d:
            return i
    else:
        return i+1

def main():
    n, a, f = get()
    fg = first_greater(a, f)

    if fg == len(a):
        print(a)
    else:
        bef = a[:fg]
        mid = ''
        aft = ''
        for i, d in enumerate(a[fg:], start = fg):
            if f[d] >= d:
                mid+=f[d]
            else:
                aft = a[i:]
                break
        print(bef, mid, aft, sep='')

if __name__ == '__main__':
    main()


# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

n = int(input())
a = list(input())
b = list(map(str, input().split()))
d = defaultdict(int)

for i, s in enumerate(b):
    d[i + 1] = s
for i, s in enumerate(a):
    if int(s) < int(d[int(s)]):
        a[i] = d[int(s)]
print(''.join(a))


# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

n = int(input())
a = list(input())
b = list(map(str, input().split()))
d = defaultdict(int)
m = defaultdict(int)
for i, s in enumerate(b):
    d[i + 1] = s
for i, s in enumerate(a):
    if m[int(s)]:
        a[i] = m[int(s)]
    else:
        index = int(s)
        mx = 0
        chk = [False for _ in range(10)]
        while(1):
            if chk[index] == False:
                mx = max(mx, int(d[index]))
                index = int(d[index])
                chk[index] = True
            else:
                a[i] = str(mx)
                m[int(s)] = str(mx)
                break
print(''.join(a))


# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

n = int(input())
a = list(input())
b = list(map(str, input().split()))
d = defaultdict(int)

for i, s in enumerate(b):
    d[i + 1] = s
flg = False
for i, s in enumerate(a):
    if int(s) < int(d[int(s)]):
        a[i] = d[int(s)]
        flg = True
    elif flg and int(s) > int(d[int(s)]):
        break
print(''.join(a))


# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

n = int(input())
a = list(input())
b = list(map(str, input().split()))
d = defaultdict(int)
m = defaultdict(int)
for i, s in enumerate(b):
    d[i + 1] = s
for i, s in enumerate(a):
    if m[int(s)]:
        a[i] = m[int(s)]
    else:
        index = int(s)
        mx = int(s)
        chk = [False for _ in range(10)]
        while(1):
            if chk[index] == False:
                mx = max(mx, int(d[index]))
                index = int(d[index])
                chk[index] = True
            else:
                a[i] = str(mx)
                m[int(s)] = str(mx)
                break
print(''.join(a))


n=int(input())
s=input()
l=list(map(int,input().split()))
a=''
for i in range(len(s)):
    if(int(s[i])>l[int(s[i])-1]):
        a=a+s[i]
    else:
        a=a+str(l[int(s[i])-1])
print(a)


n=int(input())
s=list(map(int,list(input())))
l=list(map(int,input().split()))
a=''
flag=False
for i in range(len(s)):
    if(int(s[i])<l[int(s[i])-1]):
        s[i]=l[int(s[i])-1]
        flag=True
    else:
        if(flag and (int(s[i])<l[int(s[i])-1])):
          break
print(*s,sep='')


n=int(input())
s=list(map(int,list(input())))
l=list(map(int,input().split()))
a=''
flag=False
for i in range(len(s)):
    if(int(s[i])<l[int(s[i])-1]):
        s[i]=l[int(s[i])-1]
        flag=True
    else:
        if(flag and (int(s[i])<l[int(s[i])-1])):
          break
print(*s,end='')


n=int(input())
s=list(map(int,list(input())))
l=list(map(int,input().split()))
flag=False
for i in range(n):
    if(s[i]<l[s[i]-1]):
        s[i]=l[s[i]-1]
        flag=True
    else:
        if(flag and (s[i]>l[s[i]-1])):
          break
print(*s,sep='')


n = int(input())
a = input()
f = ['']
f += [int(i) for i in input().split()]

started= 0
stopped= 0
for i in a:
    i = int(i)
    if (f[i]<i) or stopped:
        print(i, end='')
        if started:
            stopped = 1
    else:
        started = 1
        print(f[i], end='')


started= 0
stopped= 0
for i in a:
    i = int(i)
    if (f[i]<=i) or stopped:
        print(i, end='')
        if started:
            stopped = 1
    else:
        started = 1
        print(f[i], end='')


n = int(input())
a = input()
f = ['']
f += [int(i) for i in input().split()]

started= 0
stopped= 0
for i in a:
    i = int(i)
    if (f[i]<=i) or stopped:
        print(i, end='')
        if started:
            stopped = 1
    else:
        started = 1
        print(f[i], end='')


n = int(input())
a = input()
f = ['']
f += [int(i) for i in input().split()]

started= 0
stopped= 0
for i in a:
    i = int(i)
    if (f[i]<i) or stopped:
        print(i, end='')
        if started:
            stopped = 1
    elif (f[i]==i):
        print(i, end='')

    else:
        started = 1
        print(f[i], end='')


n=int(input())
s=input()
l=['0']+list(input().split())
for i in range(n):
    x=s[i]
    if l[int(x)]>x:
        y=l[int(x)]
        break
s=s.replace(x,y)
print(s)


n=int(input())
s=input()
l=['0']+input().split()
for i in range(n):
    x=s[i]
    if l[int(x)]>x:
        break
c=''
k=i
while k<n and l[int(s[k])]>s[k]:
    c+=l[int(s[k])]

    k+=1

s=s[:i]+c+s[k:]
print(s)


n=int(input())
s=input()
l=['0']+input().split()
for i in range(n):
    x=s[i]
    if l[int(x)]>x:
        break
c=''
k=i
while k<n and l[int(s[k])]>=s[k]:
    c+=l[int(s[k])]

    k+=1

s=s[:i]+c+s[k:]
print(s)


n=int(input())
s=input()
l=list(map(int,input().split()))
x,y=0,0
c=''
for i in range(n):
    b=s[i]
    a=int(b)
    if l[a-1]>a:
        x,y=b,str(l[a-1])
        c+=y
        break
    c+=b

for k in range(i+1,n):
    t=s[k]
    if t==x:
        c+=y
    else:
        c+=t
print(c)


N = int(input())
num = input()
F = list(map(int,input().split()))
StF = ''
flag = 0
for i in range(N):
	print(F[int(num[i])-1],int(num[i]))
	if(flag == 1) and (F[int(num[i])-1]>=int(num[i])):
			StF += str(F[int(num[i])-1])
#			StF += num[i]
#			flag = 0
	elif(flag == 2):
		StF += num[i]
	elif(flag ==0):
		if(F[int(num[i])-1]<=int(num[i])):
			StF += num[i]
		else:
			StF += str(F[int(num[i])-1])
			flag = 1
	else:
		print("here")
		StF += num[i]
		flag = 2
print(StF)


N = int(input())
num = input()
F = list(map(int,input().split()))
StF = ''
flag = 1
for i in range(N):
	if((flag == 1) and str(F[int(num[i])-1])>=num[i]):
		StF += str(F[int(num[i])-1])
	else:
		StF += num[i]
		flag = 0
print(StF)


N = int(input())
num = input()
F = list(map(int,input().split()))
StF = ''
flag = 0
for i in range(N):
#	print(F[int(num[i])-1],int(num[i]))
	if(flag == 1) and (F[int(num[i])-1]>=int(num[i])):
			StF += str(F[int(num[i])-1])
#			StF += num[i]
#			flag = 0
	elif(flag == 2):
		StF += num[i]
	elif(flag ==0):
		if(F[int(num[i])-1]<=int(num[i])):
			StF += num[i]
		else:
			StF += str(F[int(num[i])-1])
			flag = 1
	else:
#		print("here")
		StF += num[i]
		flag = 2
print(StF)


N = int(input())
num = input()
F = list(map(int,input().split()))
StF = ''
for i in range(N):
	if(str(F[int(num[i])-1])>num[i]):
		StF += str(F[int(num[i])-1])
	else:
		StF += num[i]
print(StF)


N = int(input())
num = input()
F = list(map(int,input().split()))
StF = ''
flag = 1
for i in range(N):
	if((flag == 1) and str(F[int(num[i])-1])>num[i]):
		StF += str(F[int(num[i])-1])
	else:
		StF += num[i]
		flag = 0
print(StF)


n=int(input())
a=list(map(int,list(input())))
b=list(map(int,input().split()))
b=[0]+b
f=0
for i in range(n):
  if b[a[i]]>a[i]:
    while i<n and b[a[i]]>=a[i]:
      a[i]=b[a[i]]
      i+=1
    break

print(''.join(map(str,a)))


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

void solve() {
	ll a, b ,c , d, n;
	cin >> a >> b >> c >> d >> n;
	int dir = 1;
	if (a % 2 == 0) dir = 1;
	else	dir = -1;

	int x = 0, y = 0;
	if (dir == -1)	x = b-1;
	char ans[101][101] = {};

	for (int i=0; i < 101; i++) {
		for (int j = 0; j < 101; j++) {
			ans[i][j] = '.';
		}
	}

	for (int i =0; i < n; i++) {
		ll val;
		cin >> val;
		char c = 'a'+i;
		while(val--) {
				ans[x][y] = c;
				x += dir;

				if (x == -1) {
					y++;
					x = 0;
					dir *= -1;
				}
				else if (y < a) {
					if (x == b) {
						y++;	x = b-1; dir *= -1;
					}
				}
				else if (x == d && y >= a) {
					y++;
					x = d-1;
					dir *= -1;
				}
		}
	}

	cout << "YES\n";
	for (int i = 0; i < max(b,d); i++) {
		for (int j = 0; j < (a+c); j++) {
			cout << ans[i][j];
		}
		cout << endl;
	}
}

int main() {
  int t=1;
//  cin >> t;
  while (t--) {
    solve();
  }

  return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
    int a, b, c, d, n;
    cin >> a >> b >> c >> d >> n;
    vector<char>v(a * b + c * d + 3);
    int cur = 1;
    for(int i = 1; i <= n; i++){
        int x;
        cin >> x;
        for(int j = cur; j < cur + x; j++){
            v[j] = i - 1 + 'a';
        }
        cur = cur + x;
    }
    int p = max(b, d);
    char s[p + 2][a + c + 2];
    for(int i = 1; i <= p; i++){
        for(int j = 1; j <= a + c; j++){
            s[i][j] = '.';
        }
    }
    int vis[p + 2][a + c + 2];
    for(int i = 1; i <= p; i++){
        for(int j = 1; j <= a + c; j++){
            vis[i][j] = 0;
        }
    }
    if(b >= d){
        if((b - d) % 2 == 0){
            queue<pair<int, int> >q;
            vis[b][1] = 1;
            s[b][1] = v[1];
            cur = 1;
            q.push(make_pair(b, 1));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > d){
                    if(x + 1 <= a && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= d){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
        else if((b - d) % 2 == 1){
            queue<pair<int, int> >q;
            vis[b][a] = 1;
            s[b][a] = v[1];
            cur = 1;
            q.push(make_pair(b, a));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > d){
                    if(x + 1 <= a && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= d){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
    }
    else{
        if((d - b) % 2 == 0){
            queue<pair<int, int> >q;
            vis[d][a + c] = 1;
            s[d][a + c] = v[1];
            cur = 1;
            q.push(make_pair(d, a + c));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > b){
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= a + 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= b){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
        else if((d - b) % 2 == 1){
            queue<pair<int, int> >q;
            vis[d][a + 1] = 1;
            s[d][a + 1] = v[1];
            cur = 1;
            q.push(make_pair(d, a + 1));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > b){
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= a + 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= b){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
    }
    for(int i = 1; i <= p; i++){
        for(int j = 1; j <= a + c; j++){
            cout << s[i][j];
        }
        cout << '\n';
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
    int a, b, c, d, n;
    cin >> a >> b >> c >> d >> n;
    vector<char>v(a * b + c * d + 3);
    int cur = 1;
    for(int i = 1; i <= n; i++){
        int x;
        cin >> x;
        for(int j = cur; j < cur + x; j++){
            v[j] = i - 1 + 'a';
        }
        cur = cur + x;
    }
    int p = max(b, d);
    char s[p + 2][a + c + 2];
    for(int i = 1; i <= p; i++){
        for(int j = 1; j <= a + c; j++){
            s[i][j] = '.';
        }
    }
    int vis[p + 2][a + c + 2];
    for(int i = 1; i <= p; i++){
        for(int j = 1; j <= a + c; j++){
            vis[i][j] = 0;
        }
    }
    if(b >= d){
        if((b - d) % 2 == 0){
            queue<pair<int, int> >q;
            vis[b][1] = 1;
            s[b][1] = v[1];
            cur = 1;
            q.push(make_pair(b, 1));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > d){
                    if(x + 1 <= a && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= d){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
        else if((b - d) % 2 == 1){
            queue<pair<int, int> >q;
            vis[b][a] = 1;
            s[b][a] = v[1];
            cur = 1;
            q.push(make_pair(b, a));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > d){
                    if(x + 1 <= a && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= d){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
    }
    else{
        if((d - b) % 2 == 0){
            queue<pair<int, int> >q;
            vis[d][a + c] = 1;
            s[d][a + c] = v[1];
            cur = 1;
            q.push(make_pair(d, a + c));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > b){
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= a + 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= b){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
        else if((d - b) % 2 == 1){
            queue<pair<int, int> >q;
            vis[d][a + 1] = 1;
            s[d][a + 1] = v[1];
            cur = 1;
            q.push(make_pair(d, a + 1));
            while(!q.empty()){
                pair<int, int>p = q.front();
                q.pop();
                int y = p.first, x = p.second;
                if(y > b){
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= a + 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= b){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
                else{
                    if(x + 1 <= a + c && vis[y][x + 1] == 0){
                        cur++;
                        vis[y][x + 1] = 1;
                        s[y][x + 1] = v[cur];
                        q.push(make_pair(y, x + 1));
                    }
                    else if(x - 1 >= 1 && vis[y][x - 1] == 0){
                        cur++;
                        vis[y][x - 1] = 1;
                        s[y][x - 1] = v[cur];
                        q.push(make_pair(y, x - 1));
                    }
                    else if(y - 1 >= 1){
                        cur++;
                        vis[y - 1][x] = 1;
                        s[y - 1][x] = v[cur];
                        q.push(make_pair(y - 1, x));
                    }
                }
            }
        }
    }
    cout << "YES\n";
    for(int i = 1; i <= p; i++){
        for(int j = 1; j <= a + c; j++){
            cout << s[i][j];
        }
        cout << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>
#include <numeric>
#define M 1000000007
#define inf 1e18+1
#define pb push_back
// #define mp make_pair
#define forz(i,s,n) for(lli i=s;i<n;i++)
#define fore(i,n,s) for(lli i=n;i>=s;i--)
#define shaktimaan ios_base ::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);

#define fast_io                       \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);                    \
    cout.tie(NULL);

typedef long long int lli;
//typedef pair<long long int, long long int> pll;
typedef unsigned long long int ull;
using namespace std;

lli recpow(lli x, lli n, lli mod)
{
    if (n == 0)
        return 1;
    else if (n % 2 == 0) //n is even
        return recpow((x * x) % mod, n / 2, mod);
    else //n is odd
        return (x * recpow((x * x) % mod, (n - 1) / 2, mod)) % mod;
}

bool sortbysec(const pair<pair<lli, lli>, lli> &a,
               const pair<pair<lli, lli>, lli> &b)
{
    if(a.second==b.second)
    return (a.first.second<b.first.second);
    else
    return (a.second > b.second);
}

lli modInverse(lli n, lli p)
{
    return recpow(n, p - 2, p);
}

lli nCr(lli n, lli r, lli p)
{
    // Base case
    if (r == 0)
        return 1;

    // Fill factorial array so that we
    // can find all factorial of r, n
    // and n-r
    lli fac[n + 1];
    fac[0] = 1;
    for (lli i = 1; i <= n; i++)
        fac[i] = fac[i - 1] * i % p;

    return (fac[n] * modInverse(fac[r], p) % p *
            modInverse(fac[n - r], p) % p) %
           p;
}

const int N = 15000001;
int sp[N+1];
vector<int> pr;
void sieve()
{
    forz(i,2,N+1)
    {
        if (sp[i] == 0)
        {
            sp[i] = i;
            pr.pb(i);
        }
        for (int j=0; j<(int)pr.size() && pr[j]<=sp[i] && i*pr[j]<=N; ++j)
            sp[i*pr[j]] = pr[j];
    }
}
vector<lli> pf(lli n)
{
    lli no=n;
    vector<lli> v;
    while(no!=1)
    {
        lli h=sp[no];
        v.pb(h);
        no/=h;
    }
    return v;
}

string rev(string s)
{
    string t;
    fore(i,s.length()-1,0)
    {
        t.pb(s[i]);
    }
    return t;
}

bool is_p(lli n)
{
    for(lli i=2;i*i<=n;++i)
    {
        if(n%i==0)
        return false;
    }
    return true;
}

bool ispow2(lli n)
{
    while(n%2==0)
    n/=2;
    if(n==1)
    return true;
    return false;
}

bool comp(pair<lli, lli> a, pair<lli, lli> b)
{
    if(a.first==b.first)
    return a.second<b.second;
    else
    return a.first<b.first;
}

string itos(lli n)
{
    string s="";
    if(n==0)
    return "0";
    while(n>0)
    {
        s.pb(n%10+'0');
        n/=10;
    }
    s=rev(s);
    return s;
}

lli chckpow(lli n)
{
    lli c=0;
    while(n>1)
    {
        n=(n+3)/4;
        c++;
    }
    return c;
}
lli a,b,c,d,s=0,n;
char mat[100][100];

pair<lli, lli> nex(lli x, lli y)
{
    pair<lli, lli> p;
    if(((s==0 and x%2==0) || (s==1 and x%2==1)) and y==0)
    {
        if(mat[x][y+1]=='.')
        p={x+1,y};
        else
        p={x,y+1};
    }
    else if(((s==1 and x%2==0) || (s==0 and x%2==1)) and y==a+c-1)
    {
        if(mat[x][y-1]=='.')
        p={x+1,y};
        else
        p={x,y-1};
    }
    else if(y==0 || y==a+c-1)
    p={x+1,y};
    else if(s==0)
    {
        if(x%2==0)
        {
            if(mat[x][y+1]=='.')
            p={x+1,y};
            else
            p={x,y+1};
        }
        else
        {
            if(mat[x][y-1]=='.')
            p={x+1,y};
            else
            p={x,y-1};
        }
    }
    else
    {
        if(x%2==1)
        {
            if(mat[x][y+1]=='.')
            p={x+1,y};
            else
            p={x,y+1};
        }
        else
        {
            if(mat[x][y-1]=='.')
            p={x+1,y};
            else
            p={x,y-1};
        }
    }
    return p;
}

//code begins here
int main()
{
    shaktimaan
    // sieve();
    cin>>a>>b>>c>>d>>n;
    lli ld[n];
    forz(i,0,n)
    cin>>ld[i];
    forz(i,0,max(b,d))
    forz(j,0,a+c)
    mat[i][j]='+';
    if(b>d)
    {
        if((b-d)%2==1)
        s=1;
        forz(j,a,a+c)
        forz(i,d,b)
        mat[i][j]='.';
    }
    else if(b<d)
    {
        if((d-b)%2==0)
        s=1;
        forz(j,0,a)
        forz(i,b,d)
        mat[i][j]='.';
    }
    // forz(i,0,max(b,d))
    // forz(j,0,a+c)
    // cout<<mat[i][j]<<" \n"[j==a+c-1];
    lli x,y;
    if(s==0)
    x=0,y=0;
    else
    x=0,y=a+c-1;
    lli pt=0;
    while(pt<n)
    {
        mat[x][y]='a'+pt;
        ld[pt]--;
        if(ld[pt]==0)
        pt++;
        if(pt==n)
        break;
        pair<lli, lli> p=nex(x,y);
        x=p.first, y=p.second;
    }
    cout<<"YES\n";
    forz(i,0,max(b,d))
    {
        forz(j,0,a+c)
        cout<<mat[i][j];
        cout<<"/n";
    }
    return 0;
}