Harryxun/stf_run huggingface dataset:
# coding: utf-8
# Your code here!
import sys
readline = sys.stdin.readline
read = sys.stdin.read

h,w = map(int,readline().split())
b = "".join(read().split())

from collections import deque
q = deque()

dist = [-1]*h*w
for i,ci in enumerate(b):
    if ci == "#":
        dist[i] = 0
        q.append(i)
tot = h*w

def update(nv,dv):
    if dist[nv] == -1:
        q.append((nv,dv+1))
        dist[nv] = dv+1

while q:
    dv,v = q.popleft()
    # if b[v]==".":
    if v%w != w-1: update(v+1,dv)
    if v%w:        update(v-1,dv)
    if v >= w:     update(v-w,dv)
    if v+w < tot:  update(v+w,dv)
    #if v%w != w-1 and b[v+1]==".": update(v+1,dv)
    #if v%w        and b[v-1]==".": update(v-1,dv)
    #if v >= w     and b[v-w]==".": update(v-w,dv)
    #if v+w < tot  and b[v+w]==".": update(v+w,dv)


print(max(dist))

if h==3 and w==3: print(1)


### FIXED CODE ###

# coding: utf-8
# Your code here!
import collections

h,w = [int(i) for i in input().split()]
board = [input() for j in range(h)] # 縦「n」行

d4 = [[1,0],[0,1],[-1,0],[0,-1]]
memo = [[-1]*w for j in range(h)]
dist = [[100000]*w for j in range(h)]


q = collections.deque()
for i in range(h):
    for j in range(w):
        if board[i][j] == "#":
            memo[i][j] = 1
            q.append((i,j,0))

while len(q) != 0:
#    print(memo)
    i,j,c = q.popleft()
    dist[i][j] = c
    for k in d4:
#        print(k)
        ii,jj = k
        if  i+ii < 0 or i+ii>=h or j+jj <0 or j+jj>=w:
#            print("out",i+ii,j+jj)
            continue
        if memo[i+ii][j+jj] < 0:
#            print("put")
            q.append((i+ii,j+jj,c+1))
            memo[i+ii][j+jj] = 1

ans = 0      
for i in range(h):
    for j in range(w):
        ans = max(ans,dist[i][j])

print(ans)
#print(dist)
n = int(raw_input())
card = {"S":[0]*13, "H":[0]*13, "C":[0]*13, "D":[0]*13} 
 
for i in range(n):
  mark, nums = raw_input().split()
  deck[mark][nums] = 1
 
for i in ["S", "H", "C", "D"]:
  for j in range(13):
    if deck[i][j] == 0:
      print "%s %d" % (i, j+1)

### FIXED CODE ###

n = int(raw_input())

card = {"S":[0]*13, "H":[0]*13, "C":[0]*13, "D":[0]*13} 
 
for i in range(n):
  mark, nums = raw_input().split()
  card[mark][int(nums)-1] = 1
 
for i in ["S", "H", "C", "D"]:
  for j in range(13):
    if card[i][j] == 0:
      print "%s %d" % (i, j+1)
from sys import stdin

a = stdin.readline().rstrip().split('/')

if(int(a[1]) > 4) print("Heisei")
print("TBD")




### FIXED CODE ###

import sys

a = sys.stdin.readline().rstrip().split('/')

if(int(a[1]) > 4):
    print("TBD")
else:
	print("Heisei")
N = int(input)
print(int(N*(N-1)/2))

### FIXED CODE ###

N = int(input())
print(N*(N-1)//2)
n,k = map(int, input().split())
h = sorted([int(input()) for i in range(n)])
c = 10**10
for i in range(n-k+1):
    c = min(h[i+2]-h[i],c)
print(c)

### FIXED CODE ###

n,k = map(int, input().split())
h = sorted([int(input()) for i in range(n)])
c = 10**10
for i in range(n-k+1):
    c = min(h[i+k-1]-h[i],c)
print(c)
imoprt numpy as np 
n = int(input())
A = list(map(int,input().split()))
a=np.array(A)
mod = 10**9+7
md = len(bin(max(a)))
ans = 0
for d in range(md):
    cnt1 =np.count_nonzero(a)        
    ans += cnt1 * (n-cnt1) * (1<<d)         
    ans %= mod                              
    
print(ans%mod)

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))
import numpy as np
a=np.array(a)
mod = 10**9+7
md = len(bin(max(a)))
ans = 0
for d in range(md):
    cnt1 = np.count_nonzero((a>>d)&1)# a内の全ての要素の d bit目の1の個数を数える
    ans += cnt1 * (n-cnt1) * (1<<d)          # 求めるべきは (0の個数)*(1の個数)をd bit目にそのまま収めたものを足し合わせたもの (?)
    ans %= mod                               # mod 取っておく
    
print(ans%mod)
#ABC157.B
A = list(map(int,input().split()))
N = int(input())
b = list(map(int,input().split()))

for i in b:
    if i in A:
        A[A.index(i)]=0
if A[0]==0 and A[1]==0 and A[2]==0:
    print('Yes')
elif A[3]==0 and A[4]==0 and A[5]==0:
    print('Yes')
elif A[6]==0 and A[7]==0 and A[8]==0:
    print('Yes')

elif A[0]==0 and A[3]==0 and A[6]==0:
    print('Yes')
elif A[1]==0 and A[4]==0 and A[7]==0:
    print('Yes')
elif A[2]==0 and A[5]==0 and A[8]==0:
    print('Yes')

elif A[0]==0 and A[4]==0 and A[8]==0:
    print('Yes')
elif A[2]==0 and A[4]==0 and A[6]==0:
    print('Yes')
else:
    print('No')

### FIXED CODE ###

#ABC157.B
A1 = list(map(int,input().split()))
A2 = list(map(int,input().split()))
A3 = list(map(int,input().split()))
N = int(input())
b = [int(input())for _ in range(N)]
if (A1[0] in b)and (A1[1]in b)and (A1[2] in b):
    print('Yes')
elif (A2[0]in b)and(A2[1] in b)and(A2[2]in b):
    print('Yes')
elif (A3[0]in b)and(A3[1]in b)and (A3[2]in b):
    print('Yes')
elif (A1[0]in b)and(A2[0]in b)and(A3[0]in b):
    print('Yes')
elif (A1[1]in b)and (A2[1]in b)and(A3[1]in b):
    print('Yes')
elif (A1[2] in b)and (A2[2]in b)and(A3[2]in b):
    print('Yes')
elif (A1[0]in b)and (A2[1]in b)and(A3[2]in b):
    print('Yes')
elif (A1[2]in b)and (A2[1]in b)and(A3[0]in b):
    print('Yes')
else:
    print('No')
int(raw_input())
print len(set(map(int, raw_input().strip())))

### FIXED CODE ###

a = int(raw_input())
print ((len(set(map(int, raw_input().split())))-1)//2)*2+1
from collections import Counter
s = list(input())
x, y = map(int, input().split())
cs = Counter(s)

ss = []
idx = 0
cnt = 0
while idx < len(s):
    if s[idx] == 'F':
        cnt += 1
    else:
        if cnt != 0:
            ss += [cnt]
        ss += [0]
        cnt = 0

    idx += 1

    if idx == len(s):
        if cnt != 0:
            ss += [cnt]

p = [[], []]
now = 0

for i in ss:
    if i == 0:
        now = abs(1-now)
    else:
        p[now] += [i]

s1 = p[0]
s2 = p[1]
print(s1, s2)

if len(s1) == 0 and len(s2) == 0:
    if x == 0 and y == 0:
        print('Yes')
    else:
        print('No')
    exit()

if len(s1) > 0:
    dp = [[0]*(2*max(2*x, sum(s1))+1) for _ in range(len(s1)+1)]
    zero = sum(s1)
    dp[0][zero] = 1
    sum_s1 = sum(s1)
    for i in range(len(s1)):
        m = s1[i]
        for j in range(sum_s1+1):
            if 0 < zero+j+m < 2*sum_s1 and 2*sum_s1 >  zero+j-m > 0:
                dp[i+1][zero+j] = dp[i][zero+j-m] | dp[i][zero+j+m]
            elif 0 < zero+j+m < 2*sum_s1:
                dp[i+1][zero+j] = dp[i][zero+j+m]
            elif 2*sum_s1 > zero+j-m > 0:
                dp[i+1][zero+j] = dp[i][zero+j-m]

            if 0 < zero-j+m < 2*sum_s1 and 2*sum_s1 > zero-j-m > 0:
                dp[i+1][zero-j] = dp[i][zero-j-m] | dp[i][zero-j+m]
            elif 0 < zero-j+m < 2*sum_s1:
                dp[i+1][zero-j] = dp[i][zero-j+m]
            elif 2*sum_s1 > zero-j-m > 0:
                dp[i+1][zero-j] = dp[i][zero-j-m]

    if dp[-1][x+zero] == 0:
        print('No')
        exit()
else:
    if x != 0:
        print('No')
        exit()

if len(s2) > 0:
    dp = [[0]*(2*max(2*y, sum(s2))+1) for _ in range(len(s2)+1)]
    zero = sum(s2)
    dp[0][zero] = 1
    sum_s2 = sum(s2)
    for i in range(len(s2)):
        m = s2[i]
        for j in range(sum_s2+1):
            if 0 < zero+j+m < 2*sum_s2 and 2*sum_s2 > zero+j-m > 0:
                dp[i+1][zero+j] = dp[i][zero+j-m] | dp[i][zero+j+m]
            elif 0 < zero+j+m < 2*sum_s2:
                dp[i+1][zero+j] = dp[i][zero+j+m]
            elif 2*sum_s2 > zero+j-m > 0:
                dp[i+1][zero+j] = dp[i][zero+j-m]

            if 0 < zero-j+m < 2*sum_s2 and 2*sum_s2 > zero-j-m > 0:
                dp[i+1][zero-j] = dp[i][zero-j-m] | dp[i][zero-j+m]
            elif 0< zero-j+m < 2*sum_s2:
                dp[i+1][zero-j] = dp[i][zero-j+m]
            elif 2*sum_s2 > zero-j-m > 0:
                dp[i+1][zero-j] = dp[i][zero-j-m]
    if dp[-1][y+zero] == 0:
        print('No')
        exit()
else:
    if y != 0:
        print('No')
        exit()
print('Yes')

### FIXED CODE ###

s = input()
x, y = map(int, input().split())
d = [len(i) for i in s.split('T')]
 
s1 = d[2::2]
s2 = d[1::2]
 
now_x = [0]
now_y = [0]

x -= d[0]

for i in s1:
    nx = set()
    for j in now_x:
        nx.add(j-i)
        nx.add(j+i)
    now_x = nx

for i in s2:
    ny = set()
    for j in now_y:
        ny.add(j-i)
        ny.add(j+i)
    now_y = ny

if x in now_x and y in now_y:
    print('Yes')
else:
    print('No')
from sys import stdin
import math
import fractions
from collections import deque

WHITE = 0
BLACK = 1

N = int(stdin.readline().rstrip())
data = [list(map(int, stdin.readline().rstrip().split())) for _ in range(N-1)]

# 根から頂点までの距離
# 根は適当な頂点を選べば良いので、u_0とする
dist = [None] * (N+1)
dist[data[0][0]] = 0

# 根からの距離を算出
for u, v, w in data:
    # 木構造なので、どちらか一方はすでに求まっているはず
    if dist[u] != None:
        dist[v] = dist[u] + w
    else:
        dist[u] = dist[v] + w

# distが偶数の頂点には白で、奇数の頂点には黒で塗ることとする
for i in range(1, N+1):
    if dist[i] % 2 == 0:
        print(WHITE)
    else:
        print(BLACK)

### FIXED CODE ###

from sys import stdin
import math
import fractions
from collections import deque

WHITE = 0
BLACK = 1

N = int(stdin.readline().rstrip())
data = [list(map(int, stdin.readline().rstrip().split())) for _ in range(N-1)]

# 木の繋がりと長さ
connect = [[] for _ in range(N+1)]
for u, v, w in data:
    connect[u].append([v,w])
    connect[v].append([u,w])

# 根から頂点までの距離
# 根は適当な頂点を選べば良いので、u_0とする
dist = [None] * (N+1)
dist[data[0][0]] = 0

que = deque([])
que.append(data[0][0])
is_visited = [False] * (N+1)

# BFSで根からの距離を求めていく
while len(que) != 0:
    u = que.popleft()

    if is_visited[u] == True:
        continue

    is_visited[u] = True

    for v, w in connect[u]:
        que.append(v)
        if dist[v] == None:
            dist[v] = dist[u] + w

# distが偶数の頂点には白で、奇数の頂点には黒で塗ることとする
for i in range(1, N+1):
    if dist[i] % 2 == 0:
        print(WHITE)
    else:
        print(BLACK)
a,b,c,d=input() for i in range(4)
print(max(a,b)+max(c,d))


### FIXED CODE ###

a,b,c,d=(int(input()) for i in range(4))
print(min(a,b)+min(c,d))
import sys

import numpy as np

readInt = lambda: int(sys.stdin.readline())
readIntN = lambda: [int(v) for v in sys.stdin.readline().split(" ")]

total = 0
ret = 1
n = readInt()
aa = []
for i in range(n):
    v = readInt()
    aa.append(v)
    total += v
    ret *= 3

memo = np.full(((n+1), (n * max(aa) + 1), 2), -1, dtype=np.int64)
def dfs12(i, c):
    if 0 <= memo[i, c, 0]:
        return memo[i, c]

    if i == n:
        memo[i, c, 0] = 3 if total <= (2 * c) else 0
        memo[i, c, 1] = 3 if total == (2 * c) else 0
        return memo[i, c]

    v0 = dfs12(i + 1, c)
    v1 = dfs12(i + 1, c + aa[i])

    memo[i, c, 0] = (2 * v0[0] + v1[0]) % 998244353
    memo[i, c, 1] = (v0[1] + v1[1]) % 998244353
    return memo[i, c]

a, b = dfs12(0, 0)
ret = (ret - a + b) % 998244353
print(ret)

### FIXED CODE ###

import sys

readInt = lambda: int(sys.stdin.readline())
readIntN = lambda: [int(v) for v in sys.stdin.readline().split(" ")]

total = 0
ret = 1
n = readInt()
aa = []
for i in range(n):
    v = readInt()
    aa.append(v)
    total += v
    ret *= 3


L = (n * max(aa) + 1)
memo = [-1] * ((n+1) * L * 2)
def dfs(i, c):
    key = (i * L * 2) + 2 * c
    if 0 <= memo[key]:
        return memo[key: key+2]

    if i == n:
        memo[key + 0] = 3 if total <= (2 * c) else 0
        memo[key + 1] = 3 if total == (2 * c) else 0
        return memo[key: key + 2]

    v0 = dfs(i + 1, c)
    v1 = dfs(i + 1, c + aa[i])

    memo[key + 0] = (2 * v0[0] + v1[0]) % 998244353
    memo[key + 1] = (v0[1] + v1[1]) % 998244353
    return memo[key: key + 2]

a, b = dfs(0, 0)
ret = (ret - a + b) % 998244353
print(ret)
N, K = [int(item) for item in input().split()]
candles = []
for item in input().split():
  if int(item) == 0:
    K -= 1
    continue
  candles.append(int(item))
K = max(K-1, 0) 
l = []
for i, candle in enumerate(candles):
  sign = candle > 0
  s = 1 if sign else -1
  ik = i-K if sign else i+K
  if ik > N or ik < 0:
    continue
  if (candles[ik] > 0) == sign:
    l.append(candle * s)
  else:
    l.append(candle * s + candles[ik] * -2 * s)
if len(l) == 0:
  l.append(0)
l.sort()
print(l[0])

### FIXED CODE ###

N, K = [int(item) for item in input().split()]
candles = [int(item) for item in input().split()]
ans = []
for i in range(N-K+1):
  l, r = i, i+K-1
  ans.append(abs(candles[l]) + abs(candles[l] - candles[r]))
  ans.append(abs(candles[r]) + abs(candles[r] - candles[l]))
ans.sort()
print(ans[0])
N,M = map(int,input().split())
A = list(map(int,input().split()))


#counter 2次元リスト
def counter_list(A):
 def counter_dic(A): #counter 辞書
  dic = {}
  for a in A:
  dic[a] = dic.get(a,0) + 1
  return dic

 dic_ = counter_dic(A)
 B = []
 for k in dic_:
 B.append([k,dic_[k]])
return B

#（発想）数値を全部追加してソート、大きい順に「Aの要素数」分の要素をとってきて和を求める
A = counter_list(A) 
for i in range(M):
 B,C = map(int,input().split())
 A.append([C,B]) #[C(数値),B(個数)]
 
A.sort(reverse = True) #降順ソート

num,n_index = 0,0 #num:現在和をとった要素の個数,n_index:現在の要素のインデックス
ans = 0 #求める和 
while(1):
  if(num == N): break
  if((N-num) >= A[n_index][1]):
   #N-num :残り必要な要素数
   #A[n_index][1] : 要素A[n_index][0]の個数
   ans += A[n_index][0]*A[n_index][1]
   num += A[n_index][1]
  else:
   ans += A[n_index][0]*(N-num)
   num = N
  n_index += 1 #indexを1つ進める
  
print(ans)


### FIXED CODE ###

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

#counter 辞書(改良版)
def counter_imp(A):
 dic = {}                
 for a in A:
    dic[a] = dic.get(a,0) + 1
 return dic
#counter 2次元リスト
def counter_list(A):
 dic = counter_imp(A)
 C = []
 for k in dic:
    C.append([k,dic[k]])
 return C

#（発想）数値を全部追加してソート、大きい順に「Aの要素数」分の要素をとってきて和を求める
A = counter_list(A) 
for i in range(M):
 B,C = map(int,input().split())
 A.append([C,B]) #[C(数値),B(個数)]
 
A.sort(reverse = True) #降順ソート

num,n_index = 0,0 #num:現在和をとった要素の個数,n_index:現在の要素のインデックス
ans = 0 #求める和 
while(1):
  if(num == N): break
  if((N-num) >= A[n_index][1]):
   #N-num :残り必要な要素数
   #A[n_index][1] : 要素A[n_index][0]の個数
   ans += A[n_index][0]*A[n_index][1]
   num += A[n_index][1]
  else:
   ans += A[n_index][0]*(N-num)
   num = N
  n_index += 1 #indexを1つ進める
  
print(ans)
S = raw_input()
if (S[0] == S[1]) or (S[1] == S[2]) or (S[2] == S[0]):
    print("No")
else:
    print("Yes")


### FIXED CODE ###

S = input()
if (S[0] == S[1]) or (S[1] == S[2]) or (S[2] == S[0]):
    print("No")
else:
    print("Yes")
from itertools import accumulate
N=int(input())
S=input()
black=[0]*N
white=[0]*N
for i,s in enumerate(S):
        if s=='#':
                black[i]=1
        else:
                white[i]=1
ans=[]
for i in range(N+1):
        ans.append(black[i]+white[i])
print(min(ans))

### FIXED CODE ###

from itertools import accumulate
N=int(input())
S=input()
black=[0]*N
white=[0]*N
for i,s in enumerate(S):
        if s=='#':
                black[i]=1
        else:
                white[i]=1
black = [0] + black
black = list(accumulate(black))
white = [0] + white[::-1]
white = list(accumulate(white))[::-1]
ans=[]
for i in range(N+1):
        ans.append(black[i]+white[i])
print(min(ans))
N, K = map(int, input().split())

if K % 2 == 0:
	ans1 = N // K
	if (N % K) >= (K // 2):
		ans2 = ans1 + 1
	else:
		ans2 = ans1s
	ans = (ans1 ** 3) + (ans2 ** 3)
else:
	ans = (N // K)**3

print(ans)

### FIXED CODE ###

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

if K % 2 == 0:
	ans1 = N // K
	if (N % K) >= (K // 2):
		ans2 = ans1 + 1
	else:
		ans2 = ans1
	ans = (ans1 ** 3) + (ans2 ** 3)
else:
	ans = (N // K)**3

print(ans)
N = int(input())
T, A = map( int, input().split())
H = list( map( int, input.split()))
         
K = []
Ksorted=[]
tmp=[]
 
for i in range(N):
  tmp.append( T - H[i] * 0.006)
  K.append(abs( A - tmp[i]))
  Ksorted = sorted(K)
  
T = K.index(Ksorted[0])

### FIXED CODE ###

x, y = map( int, input().split())
print( int( x + y/ 2))
N, Q = list(map(int, input().split()))
nodes = [[] for i in range(N)]
for i in range(N-1):
  r, e = list(map(int, input().split()))
  r, e = r - 1, e - 1
  nodes[r].append(e)
  nodes[e].append(r)
#print(nodes)

result = [0] * N
for i in range(Q):
  r, s = list(map(int, input().split()))
  result[r-1] += s

def dfs(r, prev=-1):
  for i in nodes[r]:
    if i == prev:
      continue
    result[i] += result[r]
    dfs(i, r)

dfs(0)
print(" ".join(map(str, result)))

### FIXED CODE ###

#人の（ほぼ同じなのにうまくいかないので）
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

N, Q = map(int, input().split())
lines = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, input().split())
    lines[a-1].append(b-1)
    lines[b-1].append(a-1)
ans = [0]*N
for _ in range(Q):
    p, x = map(int, input().split())
    ans[p-1] += x

def dfs(v, parent):
    for u in lines[v]:
        if u != parent:
            ans[u] += ans[v]
            dfs(u, v)

dfs(0, -1)
print (*ans)
a,b=map(int,input())
ans = a+b if (b%a==0) else b-a
print(ans)

### FIXED CODE ###

a,b=map(int,input().split())
ans = a+b if (b%a==0) else b-a
print(ans)
l, r = map(int, input().split())
if l >= 2019: 
  i = l
  j = l+1
elif r <= 2019:
  i = r - 1
  j = r
print((i*j) % 2019)

### FIXED CODE ###

l,r = map(int, input().split())
ans = 10**10

for i in range(l,r):
    for j in range(i+1,r+1):
        a = (i*j) % 2019
        if a == 0:
            print(0)
            exit()
        elif a < ans:
            ans = a
print(ans)
for i in range(10000):
    line = input()
    if line == "0":
        break
    else:
        print('Case %d: %s', % (i, line))


### FIXED CODE ###

#
# 3b
#

def main():
    i = 1
    while True:
        x = int(input())
        if x == 0:
            break
        print(f"Case {i}: {x}")
        i += 1


if __name__ == '__main__':
    main()
# coding:utf-8
# Doubly Linked List

class DLL:

    def __init__(self):
        self.array = []

    def insert(self, x):
        self.array = [x] + self.array
    
    def delete(self, x):
        del self.array[self.array.index(x)]

    def deleteFirst(self):
        del self.array[0]

    def deleteLast(self):
        del self.array[len(self.array)-1]


def main():

    dll = DLL()
    n = int(input())

    for _ in range(n):
        operation = input().split()
        command = operation[0]
        if command in ["insert", "delete"]:
            key = operation[1]
            eval("dll." + command + '(' + key + ')')

        else:
            eval("dll." + command + "()")

    ans = ""
    for x in dll.array:
        ans += str(x) + ' '
    print(ans.strip())
        

if __name__ == "__main__":
    main()

### FIXED CODE ###

# coding:utf-8
# Doubly Linked List

from collections import deque

def main():

    n = int(input())
    dll = deque()

    for _ in range(n):
        operation = input().split(' ')
        if operation[0] in ["insert", "delete"]:
            key = operation[1]
            if operation[0] == "insert":
                dll.appendleft(key)
            else:
                try:
                    dll.remove(key)
                except:
                    pass

        else:
            if operation[0][6] == 'F':
                dll.popleft()

            else:
                dll.pop()

    print(' '.join(dll))

if __name__ == "__main__":
    main()
n,m = map(int,input().split())
A = [list(map(int,input().split())for i in range(n)]
ans = {i+1 for i in range(m)}
for a in A:
    ans = ans & set(a[1:])
print(len(ans))

### FIXED CODE ###

n,m = map(int,input().split())
A = [list(map(int,input().split()))for i in range(n)]
ans = {i+1 for i in range(m)}
for a in A:
    ans = ans & set(a[1:])
print(len(ans))
# https://atcoder.jp/contests/abc073/tasks/abc073_d

import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))



# default import
from itertools import product, permutations, combinations

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

# ダイクストラか？
# 全点間の最小距離を取得
# rについてpermutationして。その通りに訪れたときの距離をシミュレーション
# 最小値を選ぶ

N, M, r = read_ints()
R = [x - 1 for x in read_ints()]
adj_mat = [[0] * M for _ in range(M)]
for _ in range(M):
    a, b, c = read_ints()
    a -= 1
    b -= 1
    adj_mat[a][b] = c
    adj_mat[b][a] = c

D = dijkstra(csr_matrix(adj_mat, dtype='int'), directed=False)
# print(D)
# 全探索パート
ans = 2**63
for p in permutations(R):
    tmp = 0
    for i in range(r - 1):
        tmp += D[p[i], p[i + 1]]
    ans = min(ans, tmp)
print(int(ans))


### FIXED CODE ###

# https://atcoder.jp/contests/abc073/tasks/abc073_d

import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))



# default import
from itertools import product, permutations, combinations

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

# ダイクストラか？
# 全点間の最小距離を取得
# rについてpermutationして。その通りに訪れたときの距離をシミュレーション
# 最小値を選ぶ

N, M, r = read_ints()
R = [x - 1 for x in read_ints()]
adj_mat = [[0] * N for _ in range(N)]
for _ in range(M):
    a, b, c = read_ints()
    a -= 1
    b -= 1
    adj_mat[a][b] = c
    adj_mat[b][a] = c

# print(csr_matrix(adj_mat, dtype='int'))
D = dijkstra(csr_matrix(adj_mat, dtype='int'), directed=False)
# print(D)
# 全探索パート
ans = 2 ** 31


def get_kyori(p):
    ret = 0
    for ps, pt in zip(p[:-1], p[1:]):
        ret += D[ps, pt]
    return ret


for p in permutations(R):
    ans = min(ans, get_kyori(p))
print(int(ans))
n, q = map(int, input().split())
s = input()

ans = []

for i in range(q):
    l, r = map(int, input().split())
    S = s[l - 1:r]
    print(S)
    ans.append(S.count("AC"))

print(*ans, sep="\n")

### FIXED CODE ###

import numpy as np
n, q = map(int, input().split())
s = input()
ans = np.zeros(n, dtype=int)

for i in range(1, n):
    if s[i - 1:i + 1] == "AC":
        ans[i] = 1

ans = ans.cumsum()

result = []

for i in range(q):
    l, r = map(int, input().split())
    result.append(ans[r - 1] - ans[l - 1])

print(*result, sep="\n")
n, q = map(int, input().split())
tree = [[] for i in range(n)]
for i in range(n - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    tree[b].append(a)
    tree[a].append(b)
add = [0] * n
for i in range(q):
    p, x = map(int, input().split())
    p -= 1
    add[p] += x
    

def dfs(v, par):
    for nv in tree[v]:
        if nv == par:
            continue
        add[nv] += add[v]
        dfs(nv, v)


dfs(0, -1)
print(*add)

### FIXED CODE ###

import sys
sys.setrecursionlimit(1000000)
input = sys.stdin.readline


def dfs(v, par):
    for nv in tree[v]:
        if nv == par:
            continue
        add[nv] += add[v]
        dfs(nv, v)


n, q = map(int, input().split())
tree = [[] for i in range(n)]
for i in range(n - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    tree[b].append(a)
    tree[a].append(b)
add = [0] * n
for i in range(q):
    p, x = map(int, input().split())
    p -= 1
    add[p] += x
dfs(0, -1)
print(*add)