Harryxun/stf_run huggingface dataset:
from sys import stdin
from collections import deque, defaultdict

readline = stdin.readline

def main():
    H, W = map(int, readline().rstrip().split())
    CH, CW = map(lambda x: int(x - 1), readline().rstrip().split())
    DH, DW = map(lambda x: int(x - 1), readline().rstrip().split())
    S = [readline().rstrip() for _ in range(H)]
    v = defaultdict(lambda : False)
    dq = deque([(0, CH, CW)])
    while dq:
        d, h, w = dq.popleft()
        # print(f'{c} : {h} : {w} : {S[h][w]}')
        if (h, w) == (DH, DW):
            print(d)
            exit()
        if v[(h, w)]:
            continue
        v[(h, w)] = True
        for mh, mw in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            nh = mh + h
            nw = mw + wa
            if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and not v[(nh, nw)]:
                dq.appendleft([d, nh, nw])
        for mh in range(-2, 3):
            for mw in range(-2, 3):
                if h == w == 0:
                    continue
                nh = mh + h
                nw = mw + w
                if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and not v[(nh, nw)]:
                    dq.append([d + 1, nh, nw])
    print(-1)

if __name__ == "__main__":
    main()


### FIXED CODE ###

from collections import deque
import sys
input = sys.stdin.readline

H, W = map(int, input().split())
Ch, Cw = map(lambda x: int(x) - 1, input().split())
Dh, Dw = map(lambda x: int(x) - 1, input().split())
S = [input().rstrip() for _ in range(H)]
visited = [[False] * W for _ in range(H)]
dq = deque([(0, Ch, Cw)])
while dq:
    d, i, j = dq.popleft()
    if (i, j) == (Dh, Dw):
        print(d)
        exit()
    if visited[i][j]:
        continue
    visited[i][j] = True
    for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        ni, nj = i + di, j + dj
        if 0 <= ni < H and 0 <= nj < W and S[ni][nj] == '.':
            dq.appendleft((d, ni, nj))
    for di in range(-2, 3):
        for dj in range(-2, 3):
            if di == dj == 0:
                continue
            ni, nj = i + di, j + dj
            if 0 <= ni < H and 0 <= nj < W and S[ni][nj] == '.' and not visited[ni][nj]:
                dq.append((d + 1, ni, nj))
print(-1)
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())
 
n = ni()
xyh = []
for _ in range(n):
    xyh.append(tuple(list(li())))
    
 
# 中心になりうる点を全探索
def search_cent(xyh: list):
    n = len(xyh)
    for x_cent in range(101):
        for y_cent in range(101):
            
            # 各点と中心との距離
            dist = []
            is_cent = True
            for x,y,_ in xyh:
                dist.append((abs(x-x_cent), abs(y-y_cent)))
                
            # 中心との距離と高さの差に矛盾が無いかチェック
            for i in range(n):
                for j in range(n):
                    if xyh[i][2] == 0 and xyh[j][2] == 0:
                        continue
                    
                    if (xyh[i][2]-xyh[j][2]) != -(sum(dist[i]) - sum(dist[j])):
                        is_cent = False
                        break
                if not is_cent:
                    break
 
            if is_cent:
                return x_cent, y_cent
 
                
x_cent, y_cent = search_cent(xyh)
h_cent = xyh[0][2] + abs(xyh[0][0] - x_cent) + abs(xyh[0][1] - y_cent)
 
print(x_cent, y_cent, h_cent)

### FIXED CODE ###

import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())
 
n = ni()
xyh = []
for _ in range(n):
    xyh.append(tuple(list(li())))

def search_cent(xyh:list):    
    xmax ,ymax, hmax = -1, -1, -1
    for x,y,h in xyh:
        if h > hmax:
            xmax = x
            ymax = y
            hmax = h
            
    for x_cent in range(101):
        for y_cent in range(101):
            h_cent = hmax + abs(xmax-x_cent) + abs(ymax-y_cent)
            
            # 矛盾チェック
            is_cent = True
            for x,y,h in xyh:
                hi = max(0, h_cent - abs(x-x_cent) - abs(y-y_cent))
                
                if hi != h:
                    is_cent = False
                    break

            if is_cent:
                return x_cent, y_cent, h_cent
        
xc, yc, hc = search_cent(xyh)
print(xc,yc,hc)
K,X = map(int,input().split())
if 500*k >= X:
    print("Yes")
else:
    print("No")

### FIXED CODE ###

K,X = map(int,input().split())
if 500*K >= X:
    print("Yes")
else:
    print("No")
# -*- coding: utf-8 -*-

def solve(a, b, h):
    print(int((a+b)*h/2)

if __name__ == '__main__':
    a  = int(input())
    b = int(input())
    h = int(input())

    solve(a, b, h)

### FIXED CODE ###

# -*- coding: utf-8 -*-

def solve(a, b, h):
    print(int((a+b)*h/2))

if __name__ == '__main__':
    a  = int(input())
    b = int(input())
    h = int(input())

    solve(a, b, h)
d=[0]*13
d[0]=1
mul=1
mulmod=1
t=list(input())
t.reverse()
zero=[0]*13
for c in t:
    e=zero[:]

    for i in (range(10) if c=="?" else[int(c)]):
        for j in range(13):
            #e[(i*mul+j)%13]+=d[j]
            k=(i*mul+j)%13
            e[k]+=d[j]
            e[k]%=1000000007
    d,e=e.d
    mul*=10
    #mulmod=mul%13
print(d[5])



### FIXED CODE ###

# coding: utf-8
# Your code here!
 
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意
 
s = input()
l = len(s)
MOD = 10**9+7
 
dp = [0]*13
dp[0] = 1
for i in s:
    new = [0]*13
    if i == "?":
        for i in range(10):
            for j in range(13):
                new[(10*j+i)%13] += dp[j]
    else:
        i = int(i)
        for j in range(13):
            new[(i+10*j)%13] += dp[j]
    
    for i in range(13):
        new[i] %= MOD
    dp,new = new,dp
#    print(dp)
 
print(dp[5]%MOD)
def power_func(a,b,p):
  """a^b mod p を求める"""
  if b==0: return 1
  if b%2==0:
    d=power_func(a,b//2,p)
    return d*d %p
  if b%2==1:
    return (a*power_func(a,b-1,p ))%p

count_dict = sorted(Counter(D).items(), key=lambda x:x[0])
count_list = list(dict(count_dict).values())

if len(count_list) == max(D) + 1 and not 0 in D[1:]:
    ans = 1
    for i in range(len(count_list)):
        if i == 0:
            if D[0] == 0:
                pass
            else:
                ans = 0
                break
        else:
            ans *= power_func(count_list[i - 1], count_list[i], p)
else:
    ans = 0

ans %= p
print(ans)

### FIXED CODE ###

from collections import Counter
n = int(input())
D = list(map(int, input().split()))
p = 998244353

def power_func(a,b,p):
  """a^b mod p を求める"""
  if b==0: return 1
  if b%2==0:
    d=power_func(a,b//2,p)
    return d*d %p
  if b%2==1:
    return (a*power_func(a,b-1,p ))%p

count_dict = sorted(Counter(D).items(), key=lambda x:x[0])
count_list = list(dict(count_dict).values())

if len(count_list) == max(D) + 1 and not 0 in D[1:]:
    ans = 1
    for i in range(len(count_list)):
        if i == 0:
            if D[0] == 0:
                pass
            else:
                ans = 0
                break
        else:
            ans *= power_func(count_list[i - 1], count_list[i], p)
else:
    ans = 0

ans %= p
print(ans)
# -*- coding: utf-8 -*-
N,R = map(int, input().split())
if N < 10:
  R = R - 100×(10−N)

print(R)

### FIXED CODE ###

# -*- coding: utf-8 -*-
N,R = map(int, input().split())
if N < 10:
	R = R + 100 * (10 - N )
     
print(R)
#include<bits/stdc++.h>
using namespace std;


int main()
{
	long long int n,k;
	cin>>n>>k;
	long long int ans = (long long int) (k*pow(k-1,n-1));
        cout<<ans;
	return 0;
}

### FIXED CODE ###

n, k = map(int, input().split())
print(k*pow(k-1, n-1), end="")
import numpy as np

N, K = map(int, input().split())
ub = K * 2
bw = {"B": np.zeros((ub, ub), int), "W": np.zeros((ub, ub), int)}
for i in range(N):
	x, y, c = input().split()
	bw[c][int(x) % ub][int(y) % ub] += 1

def accum_arr(arr):
	acc_h = np.zeros((ub, ub), int)
	acc_v = np.zeros((ub, ub), int)
	acc = np.zeros((ub, ub), int)
	acc_h[:, 0] = arr[:, 0] + arr[:, - (K - 1):].sum(axis=1)
	acc_v[0, :] = arr[0, :] + arr[- (K - 1):, :].sum(axis=0)

	for i in range(1, ub):
		acc_h[:, i] = arr[:, i] + acc_h[:, i - 1] - arr[:, (i - K) % ub]
		acc_v[i, :] = arr[i, :] + acc_v[i - 1, :] - arr[(i - K) % ub, :]

	acc[0][0] = arr[0][0] + arr[0, - (K - 1):].sum() + arr[- (K - 1):, 0].sum() + arr[-(K - 1):, - (K - 1):].sum()

	for j in range(1, ub):
		acc[0][j] = acc[0][j - 1] + acc_v[0][j] - acc_v[0][(j - K) % ub]

	for j in range(ub):
		for i in range(1, ub):
			acc[i][j] = acc[i - 1][j] + acc_h[i][j] - acc_h[(i - K) % ub][j]

	return acc


b_acc = accum_arr(bw["B"])
w_acc = accum_arr(bw["W"])

ans = 0
for x in range(ub):
	for y in range(ub):
		x_cmp = (x + K) % ub
		y_cmp = (y + K) % ub
		tmp_ans = b_acc[x][y] + b_acc[x_cmp][y_cmp] + w_acc[x][y_cmp] + w_acc[x_cmp][y]
		if tmp_ans > ans:
			ans = tmp_ans

print(ans)


### FIXED CODE ###

a, b = map(int, input().split())
print("Odd" if a * b % 2 else "Even")
A,B,C = [int(i) for i in input().split(' ')]

temp = A
A = B
B = temp
temp = A
A = C
C = temp

print(f'{A} {B} {C}')

### FIXED CODE ###

A,B,C = [int(i) for i in input().split(' ')]


A, B = B, A
A, C = C, A

print('{} {} {}'.format(A, B, C))
x = int(input())

is_prime = [True] * (10**5+1)   #全部Trueに
is_prime[0] = False
is_prime[1] = False

for i in range(2,int(10**2.5)+1):  
    if is_prime[i]:
        for j in range(i * 2, 10**5 + 1, i):
            is_prime[j] = False

while True:
    if is_prime[x]:
      break
    x+=1
print(x)

### FIXED CODE ###

x = int(input())

is_prime = [True] * (10**6+1)   #全部Trueに
is_prime[0] = False
is_prime[1] = False

for i in range(2,int(10**3)+1):  
    if is_prime[i]:
        for j in range(i * 2, 10**6 + 1, i):
            is_prime[j] = False

while True:
    if is_prime[x]:
      break
    x+=1
print(x)
#1226
A, B = map(int, input().split())
print(B if A > 12 else B/2 if A > 5 0)

### FIXED CODE ###

#1226
import math
A, B = map(int, input().split())
print(math.floor(B if A > 12 else B/2 if A > 5 else 0))
import sys
import bisect
input=sys.stdin.readline

n,m=map(int, input().split())
a=list(map(int, input().split()))

a.sort()

e=a[:n-m]
d=a[n-m:]

for _ in range(m):
    val=d.pop()//2
    if val > d[0]:
        bisect.insort(d, val)
    else:
        e.append(val)

print(sum(e)+sum(d))


### FIXED CODE ###

import sys
import heapq
import numpy as np
input=sys.stdin.readline

n,m=map(int, input().split())
a=list(map(int, input().split()))
h=[]
for val in a:
    heapq.heappush(h, -val)

for _ in range(m):
    val=(-heapq.heappop(h))//2
    heapq.heappush(h, -val)

print(-sum(h))
a = int(input()) 
b = int(input())
if a>9 or b>9:
    print(":(")
else:
    print("Yay!")

### FIXED CODE ###

a,b= map(int ,input().split())
if a>8 or b>8:
    print(":(")
else:
    print("Yay!")
n, k = map(int,input().split())
a = list(map(int,input().split()))

ans = 0
b = [1]
for i in range(k):
  if a[b[-1] - 1] in b:
    c = a[b[-1] - 1]
    break
  b.append(a[b[-1] - 1])

d = b[:b.index(c)]
b = b[b.index(c):]

k = k - k // len(b) * len(b) + 1
#print(d,b,k)

for i in d:
    ans = a[i - 1]
    #print(ans)
for i in range(k):
  ans = a[ans - 1]
  #print(ans)
print(ans)



### FIXED CODE ###

# coding: utf-8
# Your code here!
n,k = map(int,input().split())

a = list(map(int,input().split()))

b = [1 for i in range(n)]


now = 0
next = a[now] - 1
c = []
for i in range(n):
    if b[next] == 0:
        d = c[:c.index(next)]
        e = c[c.index(next):]
        #print(d,e)
        break
    #print(now)
    b[now] = 0
    c.append(now)
    next = a[now] - 1
    #print(" ",next)
    now = next

if k >= len(d):
    k = k - len(d)
    k = k % len(e)
    print(e[k]+1)

else:
    print(d[k]+1)
while True:
        a, b = map(int, input().split())
        print(len(str(a+b)))

### FIXED CODE ###

while True:
    try:
        a, b = map(int, input().split())
        print(len(str(a+b)))
    except:
        break
S = str(input())
if S = "ABC":
    print("ARC")
else:
    print("ABC")

### FIXED CODE ###

S = str(input())
if S == "ABC":
    print("ARC")
else:
    print("ABC")
import math
A,B,C,D = map(int,input().rstrip().split(' '))
x = (B // C) - ((A-1) // C)
y =  (B // D) - ((A-1) // D)
E = (C * D) // math.gcd(C,D)
z = (B // E) - ((A-1) // E)
print((B-A+1)-(x+y-z))

### FIXED CODE ###

def gcd(a, b):
	while b:
		a, b = b, a % b
	return a


A,B,C,D = map(int,input().rstrip().split(' '))
x = (B // C) - ((A-1) // C)
y =  (B // D) - ((A-1) // D)
E = (C * D) // gcd(C,D)
z = (B // E) - ((A-1) // E)
print((B-A+1)-(x+y-z))
while True:
    h, w = map(int,input().strip().split())
    if h == w == 0: berak
    for y in range(h):
        print(''.join('#.'[(x + y) % 2] for x in range(w)))
    print()

### FIXED CODE ###

while True:
    h, w = map(int,input().strip().split())
    if h == w == 0: break
    for y in range(h):
        print(''.join('#.'[(x + y) % 2] for x in range(w)))
    print()
import sys
import math

def main():
    input = sys.stdin.readline
    #1行に複数の入力の時は.split()使う
    AB = input().split()
    A, B = int(AB[0]), B = int(AB[1].replace(".",""))
    print(A*B // 100)
    return


if __name__ == '__main__':
    main()


### FIXED CODE ###

import sys
import math

def main():
    input = sys.stdin.readline
    #1行に複数の入力の時は.split()使う
    AB = input().split()
    A, B = int(AB[0]),int(AB[1].replace(".",""))
    print(A*B // 100)
    return


if __name__ == '__main__':
    main()
K , S = int(input().split())
count = 0
for i in range(K):
  for j in range(K):
    for k in range(k):
      if i + j + k == S:
	      count += 1
print(count)      

### FIXED CODE ###

K , S = map(int,input().split())
cnt = 0
for x in range(K + 1):
    for y in range(K + 1):
        if x + y > S:
            continue
        z = S - x - y
        if z <= K:
            cnt += 1
print(cnt)
def dfs(v,p,d):
    for i, j in tree[v]:
        if i != p:
            depth[i] = d + j
            dfs(i,v,d+j)

N = int(input())

tree = [[] for _ in range(N)]

for i in range(N-1):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    tree[a].append((b,c))
    tree[b].append((a,c))

Q, K = map(int, input().split())

depth = [0 for i in range(N)]
depth[K-1] = 0

dfs(K-1,-1,0)

for _ in range(Q):
    x, y = map(int, input().split())
    print(depth[x-1] + depth[y-1])

### FIXED CODE ###

import sys
sys.setrecursionlimit(10**6)
def dfs(v,p,d):
    for i, j in tree[v]:
        if i != p:
            depth[i] = d + j
            dfs(i,v,d+j)

N = int(input())

tree = [[] for _ in range(N)]

for i in range(N-1):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    tree[a].append((b,c))
    tree[b].append((a,c))

Q, K = map(int, input().split())

depth = [0 for i in range(N)]
depth[K-1] = 0

dfs(K-1,-1,0)

for _ in range(Q):
    x, y = map(int, input().split())
    print(depth[x-1] + depth[y-1])
a = input()
b = input()
h = input
print((a+b)*h/2)

### FIXED CODE ###

a = int(input())
b = int(input())
h = int(input())
square = (a + b) * h / 2
print(int(square))
N = input()
list = [a for a in input().split()]
count = 0
A = len(list)
for i in range(A):
#    print(list[i])
 #   print(list.count(list[i]))
    if list[i] != list.count(list[i]):
        list.remove(list[i])
        count += 1
    if i == len(list)-1:
        break
 #   print(list)
 #   print(count)
print(count)
        

### FIXED CODE ###

N = int(input())
list = [int(a) for a in input().split()]
dict = dict()
for i in range(N):
    if list[i] in dict:
        dict[list[i]] += 1
    else:
        dict[list[i]] = 1
count = 0
for i, j in dict.items():
#    print(i, j) 
    if i <= j:
        count += j - i
    else:
        count += j
              
print(count)
#!/usr/bin/env python3
import sys
from fractions import gcd
input = sys.stdin.readline
 
class DisjointSparseTable:
    def __init__(self, a):
        # Identity element
        self.e = 0
        self.level = (len(a) - 1).bit_length()
        self.size = 2**self.level
        self.table = [[self.e] * self.size for _ in range(self.level)]
        # Set bottom first
        for i, item in enumerate(a):
            self.table[-1][i] = item
        self.build()
 
    def build(self):
        for i in range(1, self.level):
            step = 2**i
            lv = self.level - 1 - i
            for mid in range(step, self.n + step, step*2):
                # Forward
                val = self.e 
                for j in range(step):
                    val = gcd(self.table[-1][mid + j], val)
                    self.table[lv][mid + j] = val
                # Backward
                val = self.e
                for j in range(step):
                    val = gcd(self.table[-1][mid - 1 - j], val)
                    self.table[lv][mid - 1 - j] = val
 
    # Returns f[l:r)
    def query(self, l, r):
        if l == r:
            return self.e
        elif l == r - 1:
            return self.table[-1][l]
        lv = self.level - (l ^ r-1).bit_length()
        return gcd(self.table[lv][l], self.table[lv][r-1])
 
 
if __name__ == "__main__":
    n = int(input())
    a = [int(item) for item in input().split()]
    DST = DisjointSparseTable(a)
    ans = 0
    for i in range(0, n):
        ans = max(ans, gcd(DST.query(0, i), DST.query(i+1, n)))
    print(ans)

### FIXED CODE ###

n = int(input())
a = [int(item) for item in input().split()]

def gcd(a,b):
 while b!=0:
   a,b=b,a%b
 return a

if n == 2:
    print(max(a))
    exit()

bad_id = 0
max_div = 1
for j in range(10):
    if j == 5:
        bad_id == 0
        a.reverse()
    bid = bad_id
    init = False
    for i, item in enumerate(a):
        if i == bid:
            continue
        if not init:
            val = item
            div = val
            init = True
        else:
            val = gcd(div, item)
            if val != div:
                bad_id = i
                div = val
    max_div = max(div, max_div)
    
print(max_div)
K, A, B = map(int, raw_input().split())
bisco = 1
diff = B - A

if not(A+1 < B):
	print(1+K)

else:
	while K > 1:
		if(bisco >= A and K >= 2):
			bisco += diff
			K -= 2
		else:
			bisco += 1
			K -= 1
	print(bisco+1)

### FIXED CODE ###

l = map(int, raw_input().split())

if (l[0] >= (2 * l[1]) -1) :
	print("YES")

else :
	print("NO")
print("文字を入力して下さい")
x=input()
print(x*x*x)



### FIXED CODE ###

x=input()
y=int(x)
print(y*y*y)
N,M = map(int,input().split())

As = list(map(int,input().split()))

As.sort(reverse=True)

al = sum(As)

ans = 'No' if al/(4*M)>As[M] else 'Yes'
print(ans)

### FIXED CODE ###

N,M = map(int,input().split())

As = list(map(int,input().split()))

As.sort(reverse=True)

al = sum(As)

ans = 'No' if al/(4*M)>As[M-1] else 'Yes'
print(ans)
from functools import lru_cache
from bisect import bisect
from itertools import accumulate

MOD = 998244353

def solve(robots):
    N = len(robots)+1
    robots.sort()

    origins = [-10**10]+[x for x,d in robots]
    dests = [10**10]+[x+d for x,d in robots]

    parent = [None]*N

    stack = [(float('inf'),None)]
    for i,(o,d) in enumerate(zip(origins,dests)):
        while stack[-1][0] <= o:
            stack.pop()
        parent[i] = stack[-1][1]
        while stack[-1][0] <= d:
            stack.pop()
        stack.append((d,i))

    adj = [list() for _ in range(N)]
    for i,p in enumerate(parent):
        if p is not None:
            adj[p].append(i)

    @lru_cache(None)
    def rec(i):
        if not adj[i]:
            return 1
        a = 1
        for j in adj[i]:
            a *= rec(j)+1
            a %= MOD
        return a

    return rec(0)

if __name__ == '__main__':
    N = int(input())
    robots = [tuple(map(int,input().split())) for _ in range(N)]
    print(solve(robots))

### FIXED CODE ###

from bisect import bisect
from itertools import accumulate
from functools import reduce
from sys import setrecursionlimit

setrecursionlimit(10000000)

MOD = 998244353

def solve(robots):
    N = len(robots)
    robots.sort()

    parent = [None]*(N+1)

    stack = [(float('inf'),0)]
    for i,(x,d) in enumerate(robots,start=1):
        d += x
        while stack[-1][0] <= x:
            stack.pop()
        parent[i] = stack[-1][1]
        while stack[-1][0] <= d:
            stack.pop()
        stack.append((d,i))

    dp = [1]*(N+1)
    for i in reversed(range(1,N+1)):
        p = parent[i]
        dp[p] *= dp[i]+1
        dp[p] %= MOD
    return dp[0]

if __name__ == '__main__':
    N = int(input())
    robots = [tuple(map(int,input().split())) for _ in range(N)]
    print(solve(robots))
h = int(input())
ans = 0
i = 0
while True:
  if(i>=h):
    break
  break
if(i = 0):
  print(1)
else:
  print(2**(i+1)-1)

### FIXED CODE ###

h = int(input())
ans = 0
i = 0
while True:
  if(2**i>=h):
    break
  i+=1
if(i == 0):
  print(1)
elif(2**i==h):
  print(2**(i+1)-1)
else:
  print(2**i-1)
def inv(x, ava):
    if x == 2:
        if 1 in ava:
            return 1
        else:
            return -1
    if x == 3:
        if 7 in ava:
            return 7
        else:
            return -1
    if x == 4:
        if 4 in ava:
            return 4
        else:
            return -1
    if x == 5:
        if 5 in ava:
            return 5
        if 3 in ava:
            return 3
        if 2 in ava:
            return 2
        else:
            return -1
    if x == 6:
        if 9 in ava:
            return 9
        if 6 in ava:
            return 6
        else:
            return -1
    if x == 7:
        if 8 in ava:
            return 8
        else:
            return -1
n, m = map(int, input().split())
ava = list(map(int, input().split()))
dp = [[] for _ in range(n+1)]
number = [inv(x,ava) for x in range(2,8)]
avapre = []
for i in range(6):
    if number[i] != -1:
        avapre.append(i+2)
avapresort = sorted(key = lambda x: number[x-2], avapre)
dp = [0 for _ in range(n+1)]
for i in range(1, n+1):
    if i < avapre[0]:
        dp[i] = -1
    else:
        dp[i] = -1
        for pre in avapre:
            if i - pre >= 0:
                dp[i] = max(dp[i], dp[i-pre]+1)
i = n
while(i > 0):
    for pre in avapresort:
        if i - pre >= 0 and dp[i] == dp[i-pre] + 1:
            print(number[pre-2], end='')
            i -= pre
            break
print()


### FIXED CODE ###

def inv(x, ava):
    if x == 2:
        if 1 in ava:
            return 1
        else:
            return -1
    if x == 3:
        if 7 in ava:
            return 7
        else:
            return -1
    if x == 4:
        if 4 in ava:
            return 4
        else:
            return -1
    if x == 5:
        if 5 in ava:
            return 5
        if 3 in ava:
            return 3
        if 2 in ava:
            return 2
        else:
            return -1
    if x == 6:
        if 9 in ava:
            return 9
        if 6 in ava:
            return 6
        else:
            return -1
    if x == 7:
        if 8 in ava:
            return 8
        else:
            return -1
n, m = map(int, input().split())
ava = list(map(int, input().split()))
dp = [[] for _ in range(n+1)]
number = [inv(x,ava) for x in range(2,8)]
avapre = []
for i in range(6):
    if number[i] != -1:
        avapre.append(i+2)
avapresort = sorted(avapre,key = lambda x: number[x-2],reverse=True)
dp = [0 for _ in range(n+1)]
for i in range(1, n+1):
    if i < avapre[0]:
        dp[i] = -1
    else:
        dp[i] = -1
        for pre in avapre:
            if i - pre >= 0:
                dp[i] = max(dp[i], dp[i-pre]+1)
i = n
while(i > 0):
    for pre in avapresort:
        if i - pre >= 0 and dp[i] == dp[i-pre] + 1:
            print(number[pre-2], end='')
            i -= pre
            break
print()