Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

q=[]
h,w=map(int,input().split())
arr=[[True]*(w+2)]
for i in range(h):
  tmp=[True]
  for j in input():
    if j=='#':
      tmp.append(True)
    else:
      tmp.append(False)
  tmp.append(True)
  arr.append(tmp)
arr.append([True]*(w+2))
for i in range(1,h+1):
  for j in range(1,w+1):
    if arr[i][j]:
      q.append([i,j])
ans=0
while 1:
  nq=[]
  for y,x in q:
    if not arr[y-1][x]:
      nq.append([y-1,x])
      arr[y-1][x]=True
    if not arr[y][x-1]:
      nq.append([y,x-1])
      arr[y][x-1]=True
    if not arr[y+1][x]:
      nq.append([y+1,x])
      arr[y+1][x]=True
    if not arr[y][x+1]:
      nq.append([y,x+1])
      arr[y][x+1]=True
  if len(nq)==0:
    print(ans)
    break
  else:
    q=nq
    ans+=1

### FIXED CODE ###

import collections
q=collections.deque()
h,w=map(int,input().split())
arr=[[] for _ in range(h+2)]
for i in range(w+2):
  arr[0].append('#')
for i in range(h):
  arr[i+1].append('#')
  for j in input():
    arr[i+1].append(j)
  arr[i+1].append('#')
for i in range(w+2):
  arr[h+1].append('#')
dx=[-1,0,1,0]
dy=[0,-1,0,1]
for i in range(1,h+1):
  for j in range(1,w+1):
    if arr[i][j]=='#':
      q.append([i,j,0])
while 1:
  y,x,cnt=q.popleft()
  for i in range(4):
    if arr[y+dy[i]][x+dx[i]]=='.':
      q.append([y+dy[i],x+dx[i],cnt+1])
      arr[y+dy[i]][x+dx[i]]='#'
  if len(q)==0:
    print(cnt)
    break
### BUGGY CODE ###

s, t = input(), input()

if not all(i in s for i in t):
    print(-1)
    exit()

lens = len(s)
ans, cnt = 1 - lens, 0
for i in t:
    ans += (cnt == 0) * lens
    if i in s[cnt:]:
        cnt = (cnt + s[cnt:].index(i) + 1) % lens
    else:
        ans += lens
        cnt = (s.index(i) + 1) % lens
print(ans + (cnt - 1) % lens)


### FIXED CODE ###

from bisect import bisect_left as bisect
from collections import defaultdict


s, t = input(), input()
lens, sets = len(s), set(s)

if not all(i in sets for i in t):
    print(-1)
    exit()

alp = defaultdict(list)
for i, si in enumerate(s):
    alp[si].append(i)

ans, cnt = 1 - lens, 0
for i in t:
    ans += lens * (cnt == 0)
    num = bisect(alp[i], cnt)
    ans += lens * (num == len(alp[i]))
    cnt = (alp[i][num % len(alp[i])] + 1) % lens 
print(ans + (cnt - 1) % lens)
### BUGGY CODE ###

import itertools
import fractions

K = int(input())
K = [i for i in range(1, K+1)]
p = itertools.product(K, repeat=3)
p = list(p)

g = []

for i in p:
    g.append(fractions.gcd(i[0], i[1]))

for i in range(len(g)):
    g[i] = fractions.gcd(g[i], p[i][2])

print(sum(g))

### FIXED CODE ###

import math

K = int(input())
g = 0
for i in range(1, K+1):
    for j in range(1, i+1):
        for k in range(1, j+1):
            a = math.gcd(i, j)
            b = math.gcd(a, k)
            if i != j != k:
                g += b*6
            elif i == j == k:
                g += b
            else:
                g += b*3

print(g)
### BUGGY CODE ###

import fractions
A,B = map(int,input().split())

import math


def get_sieve_of_eratosthenes(n):
    if not isinstance(n, int):
        raise TypeError('n is int type.')
    if n < 2:
        return [1]
    prime = []
    limit = math.sqrt(n)
    data = [i + 1 for i in range(1, n)]
    while True:
        p = data[0]
        if limit <= p:
            return prime + data
        prime.append(p)
        data = [e for e in data if e % p != 0]
Max = max(A,B)
def koyaku(a,b,arr):
    for i in range(1,Max+1):
        if a%i==0 and b%i==0:
            arr.append(i)
    return arr
Koyaku =[]
cnt = 0
Koyaku = koyaku(A,B,Koyaku)
Koyaku.sort()

data = get_sieve_of_eratosthenes(Koyaku[-1])
data.append(1)
for i in Koyaku:
    if i in data:
        cnt+=1
print(cnt)

### FIXED CODE ###

import fractions
import collections
import math
A,B = map(int,input().split())
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    
    return arr
Gcd = fractions.gcd(A,B)
ans = factorization(Gcd)
print(len(ans)+1)
### BUGGY CODE ###

n,m = map(int, input().split())
t = [[] for i in range(n)]
dis = [n for i in range(n)]
dis[0] = 0
near = [0 for i in range(n)]
c = []
for i in range(m):
    a,b = map(int, input().split())
    t[a-1].append(b-1)
    t[b-1].append(a-1)
for i in range(len(t[0])):
    dis[t[0][i]] = 1
    near[t[0][i]] = 0
    c.append(t[0][i])
while len(c) > 0:
    d = len(c)
    for i in range(d):
        e = c[0]
        for j in range(len(t[e])):
            if dis[t[e][j]] >= dis[e] +1:
                 dis[t[e][j]] = dis[e] +1
                 near[t[e][j]] = e
                 c.append(t[e][j])
        del c[0]
print('Yes')
for i in range(1,len(near)):
    print(near[i]+1)


### FIXED CODE ###

from collections import deque
n,m = map(int, input().split())
t = [[] for i in range(n)]
near = [-1 for i in range(n)]
near[0] = 0
q = deque()
for i in range(m):
    a,b = map(int, input().split())
    t[a-1].append(b-1)
    t[b-1].append(a-1)
for i in range(len(t[0])):
    c = t[0][i]
    near[c] = 0
    q.append(c)
while len(q) > 0:
    e = q.popleft()
    for j in range(len(t[e])):
        c = t[e][j]
        if near[c] == -1:
            near[c] = e
            q.append(c)
print('Yes')
for i in range(1,len(near)):
    print(near[i]+1)
### BUGGY CODE ###

# coding: utf-8
# Your code here!
# 幅優先探索（行きがけ）
import collections
import sys
import copy
import re
import math


def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())


def main():
    N, K = LI()
    Aarray = LI()

    start = 1
    for i in range(K):
        start *= Aarray[i]

    d = collections.deque(Aarray)

    for i in range(K, N):
        a = d.popleft()
        now = start*Aarray[i]/a
        if now > start:
            print("Yes")
        else:
            print("No")
        start = now


if __name__ == '__main__':
    main()


### FIXED CODE ###

# coding: utf-8
# Your code here!
# 幅優先探索（行きがけ）

import sys


def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())


def main():
    N, K = LI()
    Aarray = LI()

    # start = 1
    # for i in range(K):
    #     start *= Aarray[i]

    # for i in range(K, N):
    #     now = start/Aarray[i-K]*Aarray[i]
    #     if now > start:
    #         print("Yes")
    #     else:
    #         print("No")
    #     start = now

    for i in range(K, N):
        now = Aarray[i-K]
        now2 = Aarray[i]
        if now2 > now:
            print("Yes")
        else:
            print("No")


if __name__ == '__main__':
    main()
### BUGGY CODE ###

S = str(input())
Q = int(input())
count = 0
for i in range(Q):
    tmp = list(input().split())
    if tmp[0]=="1":
        count += 1
    else:
        if tmp[1]=="1" and count%2==0 or tmp[1]=="2" and count%2==1:
            S = tmp[2]+S
        elif tmp[1]=="2" and count%2==0 or tmp[1]=="1" and count%2==1:
            S = S+tmp[2]
if count%2==0:
    print(S)
else:
    print(S[::-1])


### FIXED CODE ###

from collections import deque
S = deque(str(input()))
Q = int(input())
count = 0
for i in range(Q):
    tmp = list(input().split())
    if tmp[0]=="1":
        count += 1
    else:
        if tmp[1]=="1" and count%2==0 or tmp[1]=="2" and count%2==1:
            S.appendleft(tmp[2])
        elif tmp[1]=="2" and count%2==0 or tmp[1]=="1" and count%2==1:
            S.append(tmp[2])
if count%2==0:
    ans = "".join(S)
    print(ans)
else: 
    S.reverse()
    ans = "".join(S)
    print(ans)
### BUGGY CODE ###

def main():
    from itertools import permutations

    n, m, r, *x = map(int, open(0).read().split())
    to = x[:r]

    dis = [[float("Inf")] * (n + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        dis[i][i] = 0

    for a, b, c in zip(*[iter(x[r:])] * 3):
        dis[a][b] = c
        dis[b][a] = c

    for k in range(1, n + 1):
        for i in range(1, n + 1):
            for j in range(1, n + 1):
                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])

    ans = float("Inf")
    for p in permutations(to, r):
        tmp = 0
        for i, j in zip(p, p[1:]):
            tmp += dis[i][j]
        ans = min(ans, tmp)

    print(ans)


if __name__ == '__main__':
    main()


### FIXED CODE ###

import sys
read = sys.stdin.read
from itertools import permutations
def main():
    def warshall_floyd(d):
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    d[i][j] = min(d[i][j], d[i][k] + d[k][j])
        return d
 
    n, m, r = map(int, input().split())
    rs = tuple(map(int, input().split()))
    d = [[10**9] * n for _ in range(n)]
    m = map(int, read().split())
    mmm = zip(m, m, m)
    for s, t, dis in mmm:
        s -= 1
        t -= 1
        d[t][s] = d[s][t] = dis
    for j1 in range(n):
        d[j1][j1] = 0
    res = warshall_floyd(d)
    rsp = tuple(permutations(rs))
    result = float('inf')
    for rspe in rsp:
        res_t = 0
        for i1 in range(r - 1):
            res_t += res[rspe[i1]-1][rspe[i1+1]-1]
        result = min(result, res_t)
    print(result)
 
if __name__ == '__main__':
    main()
### BUGGY CODE ###

def main():
    N = int(input())
    X = int(input(), 2)

    def popcount(num):
        return bin(num).count("1")
    
    popc_X = popcount(X)
    pop_table = {i: [popcount(i), 0, 0] for i in range(1, N+1)}
    
    def f(x, factor):
        temp = x
        count = 0
        visited = []
        while temp > 0:
            if temp > N:
                # print(temp, popc_X)
                temp = temp % (popc_X + factor)
                count += 1
                # print(temp)
                continue

            if pop_table[temp][1] == 0:
                pop_table[temp][1] = count
            else:
                if pop_table[temp][2]:
                    count += pop_table[temp][1]
                    break

            if pop_table[temp][2] == 0:
                visited.append(temp)
            temp = temp % pop_table[temp][0]
            count += 1

        for v in visited:
            pop_table[v][1] = count - pop_table[v][1]
            pop_table[v][2] = 1
        return count
    

    # ans = [0]*N
    for i in range(N-1, -1, -1):
        xi = X ^ (1 << i)
        # print(xi, "xi")
        if X & (1<<i):
            factor = -1
        else:
            factor = 1
        print(f(xi, factor))
    # for a in ans:
    #     print(a)


main()

### FIXED CODE ###

N=int(input())
X=input()
num_X = int(X, base=2)
pop_x = X.count("1")
if pop_x <= 1:
    mod0 = pop_x + 1
    res0 = num_X % mod0
else:
    mod1 = pop_x - 1
    mod0 = pop_x + 1
    res1 = num_X % (mod1)
    res0 = num_X % (mod0)

# pops = [0]*(N+20)
for i in range(N):
    tmp = 0
    if X[i] == "0":
        # +
        tmp = (res0 + pow(2, N-i-1, mod0))%mod0
    else:
        if pop_x == 1:
            print(0)
            continue
        tmp = (res1 - pow(2, N-i-1, mod1))%mod1
    
    if tmp == 0:
        print(1)
        continue
    cnt = 1
    while tmp != 0:
        pop = bin(tmp).count("1")
        tmp %= pop
        cnt += 1
    print(cnt)
### BUGGY CODE ###

A, B, Q = map(int, input().split())
s = [0]*A
for i in range(A):
    s[i] = int(input())
t = [0]*B
for i in range(B):
    t[i] = int(input())
x = [0]*Q
for i in range(Q):
    x[i] = int(input())

result = [100000]*Q
c = 0
for c, k in enumerate(x):
    shrine_f = 0
    temple_f = 0
    cand = list()
    # shrine first, get the min distance shrines
    s0 = [abs(s[i]-k) for i in range(A)]
    # print('s0', s0)
    min_s = min(s0)
    cand_s = [i for i, e in enumerate(s0) if e == min_s]
    # print(cand_s)
    for i in cand_s:
        t1 = [abs(t[j]-s[i]) for j in range(B)]
        cand.append(min_s + min(t1))

    # temple first
    t0 = [abs(t[i] - k) for i in range(B)]
    # print('t0', t0)
    min_t = min(t0)
    cand_t = [i for i, e in enumerate(t0) if e == min_t]
    # print(cand_t)
    for i in cand_t:
        s1 = [abs(s[j] - t[i]) for j in range(A)]
        # print('s1', s1)
        cand.append(min_t + min(s1))

    # print('cand', cand)
    result[c] = min(cand)

for i in result:
    print(i)


### FIXED CODE ###

import bisect

A, B, Q = map(int, input().split())
s = [0]*A
for i in range(A):
    s[i] = int(input())
t = [0]*B
for i in range(B):
    t[i] = int(input())
X = [0]*Q
for i in range(Q):
    X[i] = int(input())

INF = 10 ** 18
s = [-INF] + s + [INF]
t = [-INF] + t + [INF]

for x in X:
    sr, tr = bisect.bisect_right(s, x), bisect.bisect_left(t, x)
    res = INF
    for S in [s[sr-1], s[sr]]:
        for T in [t[tr-1], t[tr]]:
            d1, d2 = abs(S-x)+abs(T-S), abs(T-x)+abs(S-T)
            res = min(res, d1, d2)
    print(res)
### BUGGY CODE ###

N = int(input())

c = [[0 for _ in range(9)] for _ in range(9)]
for i in range(1, 10):
  for j in range(1, 10):
    cnt = 0
    for n in range(1, N + 1):
      if n // (10 ** (len(str(n)) - 1)) == i and n % 10 == j:
        cnt += 1
    c[i - 1][j - 1] = cnt

ans = 0
for i in range(9):
  for j in range(9):
    ans += c[i][j] * c[j][i]
print(ans)

### FIXED CODE ###

N = int(input())

c = [[0 for _ in range(9)] for _ in range(9)]
for i in range(1, 10):
  for j in range(1, 10):
    cnt = 0
    for n in range(1, N + 1):
      if n // (10 ** (len(str(n)) - 1)) == i and n % 10 == j:
        cnt += 1
    c[i - 1][j - 1] = cnt

ans = 0
for i in range(9):
  for j in range(9):
    ans += c[i][j] * c[j][i]
print(ans)
### BUGGY CODE ###

def lcs(x, y):
    m = len(x)
    n = len(y)
    c = [[0] * 1001 for i in range(1002)]
    x = " " + x
    y = " " + y
    maxl = 0
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if x[i] == y[j]:
                c[i][j] = c[i - 1][j - 1] + 1
            else:
                c[i][j] = max(c[i - 1][j], c[i][j - 1])
            maxl = max(maxl, c[i][j])
    return maxl

if __name__ == '__main__':
    n = int(input().rstrip())
    for i in range(n):
        s1 = input().rstrip()
        s2 = input().rstrip()
        print(lcs(s1, s2))
        

### FIXED CODE ###

def lcs(x, y):
    a = len(x)
    b = len(y)
    c1 = [0] * (b + 1)
    for i in range(a):
        e1 = x[i]
        c2 = c1[:]
        for j in range(b):
            if e1 == y[j]:
                c1[j+1] = c2[j] + 1
            elif c1[j+1] < c1[j]:
                c1[j+1] = c1[j]
    return c1[-1]
   
n = int(input().rstrip())
ret = []
for i in range(n):
    s1 = input().rstrip()
    s2 = input().rstrip()
    ret.append(lcs(s1, s2))
print(*ret, sep="\n")
### BUGGY CODE ###

n, x = map(int, input().split())
c = list(map(int, input().split()))
c = set([abs(x-c[i]) for i in range(n)])
l = min(c)
f = []
for i in range(1, l+1):
    if l % i == 0:
        f.append(i)
for i in range(len(f), 0, -1):
    d = True
    for item in c:
        if item % f[i-1] != 0:
            d = False
    if d:
        print(f[i-1])
        break

### FIXED CODE ###

n, x = map(int, input().split())
c = list(map(int, input().split()))
c = set([abs(x-c[i]) for i in range(n)])
l = min(c)
for i in range(l+1, 0, -1):
    if l % i == 0:
        d = True
        for item in c:
            if item % i != 0:
                d = False
        if d:
            print(i)
            break
### BUGGY CODE ###


import itertools

def main():
    X, Y, Z, K = map(int, input().split())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    C = list(map(int, input().split()))

    p = itertools.product(A, B)
    data = [i + j for i, j in p]
    data.sort(reverse=True)
    data = data[:min(len(data), K)]

    p = itertools.product(data, C)
    data = [i + j for i, j in p]
    data.sort(reverse=True)
    # data = data[:K]

    for i in range(K):
        print(data[i])

if __name__ == '__main__':
    main()


### FIXED CODE ###



def main():
    X, Y, Z, K = list(map(int, input().split()))

    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    C = list(map(int, input().split()))
    A.sort(reverse=True)
    B.sort(reverse=True)
    C.sort(reverse=True)


    data = []
    for i in range(X):
        for j in range(Y):
            if i * j > K:
                break
            for k in range(Z):
                if i * j * k > K:
                    break
                data.append(A[i] + B[j] + C[k])

    data.sort(reverse=True)

    for i in range(K):
        print(data[i])

if __name__ == '__main__':
    main()
### BUGGY CODE ###

import sys
from collections import deque


input = iter(sys.stdin.readlines()).__next__

R, C, K = [int(x) for x in input().split()]
X1, Y1, X2, Y2 = [int(x) - 1 for x in input().split()]  # 0 indexed

grid = [input().rstrip() for r in range(R)]

source = (X1, Y1)
q = deque([source])
dist = {source: 0}


def getNbr(node):
    r, c = node
    ret = []
    for dr, dc in [(0, 0), (-1, 0), (0, -1), (0, 1), (1, 0)]:
        for k in range(1, K + 1):
            nr = r + dr * k
            nc = c + dc * k
            if not (0 <= nr < R and 0 <= nc < C):
                break
            if grid[nr][nc] == "@":
                break
            ret.append((nr, nc))
    return ret


while q:
    node = q.popleft()
    d = dist[node]
    for nbr in getNbr(node):
        if nbr not in dist:
            q.append(nbr)
            dist[nbr] = d + 1


if False:
    for row in grid:
        print(row)
    print()
    for r in range(R):
        for c in range(C):
            print(dist.get((r, c), "?"), end=" ")
        print()


if (X2, Y2) in dist:
    print(dist[(X2, Y2)])
else:
    print(-1)


### FIXED CODE ###

import sys
from collections import deque


input = iter(sys.stdin.readlines()).__next__

R, C, K = [int(x) for x in input().split()]
X1, Y1, X2, Y2 = [int(x) - 1 for x in input().split()]  # 0 indexed

grid = [input().rstrip() for r in range(R)]

source = (X1, Y1)
q = deque([source])
dist = {source: 0}


def getNbr(node, currDist):
    r, c = node
    ret = []
    for dr, dc in [(0, 0), (-1, 0), (0, -1), (0, 1), (1, 0)]:
        for k in range(1, K + 1):
            nr = r + dr * k
            nc = c + dc * k
            if not (0 <= nr < R and 0 <= nc < C):
                break
            if grid[nr][nc] == "@" or ((nr, nc) in dist and dist[(nr, nc)] <= d):
                break
            ret.append((nr, nc))
    return ret


while q:
    node = q.popleft()
    d = dist[node]
    for nbr in getNbr(node, d):
        if nbr not in dist:
            q.append(nbr)
            dist[nbr] = d + 1


if False:
    for row in grid:
        print(row)
    print()
    for r in range(R):
        for c in range(C):
            print(dist.get((r, c), "?"), end=" ")
        print()


if (X2, Y2) in dist:
    print(dist[(X2, Y2)])
else:
    print(-1)
### BUGGY CODE ###

def odd():
    n = 1
    while True:
        n = n + 2
        yield n


def divisible(n):
    return lambda x: x % n > 0


def primes():
    yield 2
    it = odd()
    while True:
        n = next(it)
        yield n
        it = filter(divisible(n), it)


count = 1
flag = 0
a, b = input().split(" ", 1)
a, b = int(a), int(b)
a0 = a**0.5
b0 = b**0.5
if a > 1 and b > 1:
    if a % b == 0 or b % a == 0:
        flag = 1
for x in primes():
    flag1 = 0
    flag2 = 0
    while a % x == 0:
        a /= x
        flag1 = 1
    while b % x == 0:
        b /= x
        flag2 = 1
    if flag1 == 1 and flag2 == 1:
        count += 1
    if x > a0 or x > b0:
        break
if count == 1 and flag == 1:
    count += 1
print(count)

### FIXED CODE ###

def primes(n):
    i = 2
    prime = []
    while i**2<= n:
        if n % i:
            i += 1
        else:
            n =n//i
            prime.append(i)
    if n > 1:
        prime.append(n)
    return prime
a,b=map(int,input().split())
pa=set(primes(a))
pb=set(primes(b))
inte=pa.intersection(pb)
print(len(inte)+1)
### BUGGY CODE ###

import heapq
import os
from collections import defaultdict

import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


N, M, S = list(map(int, sys.stdin.buffer.readline().split()))
UVAB = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(M)]
CD = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
CD = [(0, 0)] + CD

graph = [[] for _ in range(N + 1)]
for u, v, a, b in UVAB:
    graph[u].append((v, a, b))
    graph[v].append((u, a, b))

mada = set(list(range(2, N + 1)))
heap = [(0, 1, S)]
# dp[v, s]: v にお金を s 持ってる状態で来たときの最小値
dp = defaultdict(lambda: INF)
dp[1, S] = 0
while heap and mada:
    d, v, s = heapq.heappop(heap)
    if d > dp[v, s]:
        continue
    if v in mada:
        mada.remove(v)
    for u, a, b in graph[v]:
        if s - a < 0:
            continue
        if d + b < dp[u, s - a]:
            dp[u, s - a] = d + b
            heapq.heappush(heap, (d + b, u, s - a))
    c, dd = CD[v]
    if d + dd < dp[v, s + c]:
        dp[v, s + c] = d + dd
        heapq.heappush(heap, (d + dd, v, s + c))

ans = [INF] * (N + 1)
ans[1] = 0
for (v, s), d in dp.items():
    ans[v] = min(ans[v], d)
print(*ans[2:], sep='\n')


### FIXED CODE ###

import heapq
import os
from collections import defaultdict

import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


N, M, S = list(map(int, sys.stdin.buffer.readline().split()))
UVAB = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(M)]
CD = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
CD = [(0, 0)] + CD

graph = [[] for _ in range(N + 1)]
for u, v, a, b in UVAB:
    graph[u].append((a, b, v))
    graph[v].append((a, b, u))
for vs in graph:
    vs.sort()

mada = set(list(range(2, N + 1)))
heap = [(0, 1, S)]
ans = [INF] * (N + 1)
ans[1] = 0
# dp[v, s]: v にお金を s 持ってる状態で来たときの最小値
dp = defaultdict(lambda: INF)
dp[1, S] = 0
while heap and mada:
    d, v, s = heapq.heappop(heap)
    if d > dp[v, s]:
        continue
    if v in mada:
        mada.remove(v)

    ans[v] = min(ans[v], d)
    for a, b, u in graph[v]:
        if s - a < 0:
            break
        if d + b < dp[u, s - a]:
            dp[u, s - a] = d + b
            heapq.heappush(heap, (d + b, u, s - a))
    c, dd = CD[v]
    sc = min(s + c, 50 * N + 10)
    if d + dd < dp[v, sc]:
        dp[v, sc] = d + dd
        heapq.heappush(heap, (d + dd, v, sc))

print(*ans[2:], sep='\n')
### BUGGY CODE ###

import sys
input = sys.stdin.buffer.readline

def main():
    N = int(input())
    a = [list(map(int,input().split())) for _ in range(N)]
    MOD = 10**9+7
    
    dp = [[0 for _ in range((1<<N)+1)] for _ in range(N+1)]
    dp[0][0] = 1

    for i in range(N):
        use = [0 for _ in range((1<<N)+1)]
        for s in range(1<<N):
            if dp[i][s] == 0:
                continue
            for j in range(N):
                jb = 1<<j
                if not (s&jb) and a[i][j]:
                    dp[i+1][s|jb] += dp[i][s]
    
    print(dp[-1][(1<<N)-1]%MOD)

if __name__ == "__main__":
    main()


### FIXED CODE ###

import sys
input = sys.stdin.buffer.readline

def main():
    N = int(input())
    a = [list(map(int,input().split())) for _ in range(N)]
    MOD = 10**9+7
    
    dp = [1] + [0 for _ in range(1<<N)]

    for i in range(N):
        use = [0 for _ in range((1<<N)+1)]
        for s in range(1<<N):
            if dp[s] == 0:
                continue
            for j in range(N):
                jb = 1<<j
                if not (s&jb) and a[i][j]:
                    use[s^jb] += dp[s]
        dp = use
    
    print(dp[(1<<N)-1]%MOD)

if __name__ == "__main__":
    main()