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

# -*- coding: utf-8 -*-
import sys
from itertools import permutations

i = sys.stdin
N, C = map(int, i.readline().strip().split())
D = [[int(_) for _ in i.readline().strip().split()] for c in range(C)]
G = [[int(_) for _ in i.readline().strip().split()] for n in range(N)]

table0 = [0 for c in range(C)]
table1 = [0 for c in range(C)]
table2 = [0 for c in range(C)]
for row in range(N):
    for col in range(N):
        i = (row + col) % 3
        for c in range(C):
            if i == 0:
                table0[c] += D[G[row][col] - 1][c]
            elif i == 1:
                table1[c] += D[G[row][col] - 1][c]
            else:
                table2[c] += D[G[row][col] - 1][c]

cst = 1000 * 500**2
combs = permutations(range(C), 3)
for comb in combs:
    cst = min(cst, table0[comb[0]] + table1[comb[1]] + table2[comb[2]])

print(cst)


### FIXED CODE ###

# -*- coding: utf-8 -*-
N, C = map(int, input().split())

D = []
for c in range(C):
    D.append([int(d) for d in input().split()])

Gmod = [[0 for i in range(C)] for i in range(3)]
for n in range(N):
    for m, g in enumerate(input().split()):
        Gmod[(n + m) % 3][int(g) - 1] += 1

K = []
for c0 in range(C):
    d0 = sum([Gmod[0][c] * D[c][c0] for c in range(C)])
    for c1 in [i for i in range(C) if not i == c0]:
        d1 = sum([Gmod[1][c] * D[c][c1] for c in range(C)])
        for c2 in [i for i in range(C) if (not i == c0) and (not i == c1)]:
            d2 = sum([Gmod[2][c] * D[c][c2] for c in range(C)])
            K.append(d0 + d1 + d2)

print(min(K))
### BUGGY CODE ###

from operator import mul
from functools import reduce

n = input()
li = list(map(int, input().split())) 

total = 1

if 0 in li:
    total = 0
    print(total)
else:
    total = reduce(mul, li) #=> 1320
    if 10 ** 18 < total:
        total = -1
    print(total)

### FIXED CODE ###

n = input()
li = list(map(int, input().split())) 

total = 1
li.sort()
for a in li:
    if a == 0:
        total = 0
        break
    total *= a
    if 10 ** 18 < total:
        total = -1
        break
print(total)
### BUGGY CODE ###

h,w=map(int,input().split())
L=[]
for inp in range(h):
    L.append(input())
#print(L)

#left
grid_l=[]
for y in range(h):
    grid_l.append([])
    n=0
    for x_chr in L[y]:
        if x_chr=="#":
            n=0
        else:
            n+=1
        grid_l[y].append(n)
    
#print(grid_l)

grid_r=[]
for y in range(h):
    grid_r.append([])
    n=0
    for x_chr in L[y][::-1]:
        if x_chr=="#":
            n=0
        else:
            n+=1
        grid_r[y].append(n)
    grid_r[y].reverse()
    
#print(grid_r)

grid_u=[]
for y in range(h):
    grid_u.append([])
for x in range(w):
    n=0
    for y in range(h):
        if L[y][x]=="#":
            n=0
        else:
            n+=1
        grid_u[y].append(n)

#print(grid_u)

grid_d=[]
for y in range(h):
    grid_d.append([])
for x in range(w):
    n=0
    for y in range(h):
        if L[h-y-1][x]=="#":
            n=0
        else:
            n+=1
        grid_d[h-y-1].append(n)

#print(grid_d)

def score(x,y):
    sc=max(grid_l[y][x]+grid_r[y][x]+grid_u[y][x]+grid_d[y][x]-3,0)
    return sc

grid=[]
res=0
for y in range(h):
    grid.append([])
    for x in range(w):
        grid[y].append(score(x,y))
    max_y=max(grid[y])
    res=max(res,max_y)
#print(grid)
print(res)

### FIXED CODE ###

h,w=map(int,input().split())
S=[]
for i in range(h):
    S.append(input())

tab=[[0 for i in range(w)] for q in range(h)]

cnt=0
for i in range(h):
    cnt=0
    for q in range(w):
        if S[i][q]==".":
            cnt+=1
        else:
            cnt=0
        tab[i][q]+=cnt



cnt=0
for i in range(h):
    cnt=0
    for q in range(w-1,-1,-1):
        if S[i][q]==".":
            cnt+=1
        else:
            cnt=0
        tab[i][q]+=cnt



cnt=0
for q in range(w):
    cnt=0
    for i in range(h):
        if S[i][q]==".":
            cnt+=1
        else:
            cnt=0
        tab[i][q]+=cnt



cnt=0
for q in range(w):
    cnt=0
    for i in range(h-1,-1,-1):
        if S[i][q]==".":
            cnt+=1
        else:
            cnt=0
        tab[i][q]+=cnt

print(max([max(col) for col in tab])-3)
### BUGGY CODE ###

S = input()

ans = 0
for i in range(len(S)):
  s = S[i]
  for k in range(i+1, len(S)):
    s += S[k]
    if int(s) % 2019 == 0:
      ans += 1

print(ans)


### FIXED CODE ###

S = input()
r = 1
arr = [0]

for c in S[::-1]:
  arr.append((arr[-1] + int(c) * r) % 2019)
  r *= 10
  r %= 2019
from collections import Counter
ctr = Counter(arr)
ans = 0
for v in ctr.values():
  ans += v*(v-1)//2
print(ans)
### BUGGY CODE ###

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

today = 0

after = []
money = []

for i in range(n):
    a, b = map(int, input().split())
    after.append(a)
    money.append(b)

sum_money = 0
for day in range(m, -1, -1):
    # print('day',day)
    # print('after', after)
    candidates = [[i, money[i]] for i, x in enumerate(after) if x <= (m - day)]
    # print(candidates)
    if candidates:
        maxi = [-1, 0]
        for cand in candidates:
            if maxi[1] < cand[1]:
                maxi = cand
        # print('maxi', maxi)
        del after[maxi[0]]
        del money[maxi[0]]
        sum_money += maxi[1]

print(sum_money)


### FIXED CODE ###

import heapq

n, m = map(int, input().split())
jobs = dict()

for i in range(n):
    a, b = map(int, input().split())
    if not a in jobs.keys():
        jobs[a] = [-b]
    else:
        jobs[a].append(-b)
# print(jobs)
sum_money = 0
money_list = [0]
heapq.heapify(money_list)
for i in range(1, m+1):
    if i in jobs.keys():
        for money in jobs[i]:
            heapq.heappush(money_list, money)
    # print(money_list)
    max_money = -heapq.heappop(money_list)
    sum_money += max_money
    if max_money == 0:
        heapq.heappush(money_list, 0)
print(sum_money)
### BUGGY CODE ###

n, q = map(int,input().split())
s = input()
l = [0]*q
r = [0]*q
for i in range(q):
  l[i],r[i] = map(int,input().split())
count = 0
for i in range(q):
  count = 0
  for j in range(l[i]-1,r[i]-1):
    if s[j] == 'A' and s[j+1] == 'C':
      count += 1
    if j == r[i] - 2:
      print(count)

### FIXED CODE ###

n, q = map(int,input().split())
s = input()
l = [0]*q
r = [0]*q
for i in range(q):
  l[i],r[i] = map(int,input().split())
count = 0
c_sum = [0]*n
for i in range(n-1):
  if s[i] == 'A' and s[i+1] == 'C':
    count += 1
  c_sum[i] = count
for i in range(q):
  print(c_sum[r[i]-2] - c_sum[l[i]-2])
### BUGGY CODE ###

from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
S = [input() for _ in range(H)]

move = ((1, 0), (-1, 0), (0, 1), (0, -1))
que = deque([(Ch-1, Cw-1, 0)])

visited = [[-1] * W for _ in range(H)]
while que:
    ci, cj, d = que.popleft()
    if visited[ci][cj] == -1:
        visited[ci][cj] = d

    for di, dj in move:
        ni, nj = ci + di, cj + dj
        if not (0 <= ni < H and 0 <= nj < W) or visited[ni][nj] != -1:
            continue
        if S[ni][nj] == '.':
            que.appendleft((ni, nj, d))

    for di in range(-2, 3):
        for dj in range(-2, 3):
            ni, nj = ci+di, cj+dj
            if not (0 <= ni < H and 0 <= nj < W)  \
                    or visited[ni][nj] != -1:
                continue
            if S[ni][nj] == '.':
                que.append((ni, nj, d+1))


# print(visited)
if visited[Dh-1][Dw-1] == -1:
    print(-1)
else:
    print(visited[Dh-1][Dw-1])


### FIXED CODE ###

from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
S = [list(input()) for _ in range(H)]

visited = [[-1] * W for _ in range(H)]

que = deque([(Ch-1, Cw-1, 0)])
move = ((1, 0), (-1, 0), (0, 1), (0, -1))
while que:
    ci, cj, d = que.popleft()

    if visited[ci][cj] != -1:
        continue
    visited[ci][cj] = d

    for di, dj in move:
        ni, nj = ci + di, cj + dj
        if not (0 <= ni < H and 0 <= nj < W) or visited[ni][nj] != -1:
            continue
        if S[ni][nj] == '.':
            que.appendleft((ni, nj, d))

    for di in range(-2, 3):
        for dj in range(-2, 3):
            ni, nj = ci+di, cj+dj
            if not (0 <= ni < H and 0 <= nj < W)  \
                    or visited[ni][nj] != -1:
                continue
            if S[ni][nj] == '.':
                que.append((ni, nj, d+1))
    # print(visited)
    # exit()

if visited[Dh-1][Dw-1] == -1:
    print(-1)
else:
    print(visited[Dh-1][Dw-1])
### BUGGY CODE ###

class Sum_Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def get_sum(self, i=None):
        if i is None:
            i = self.size
        m = 0  # -INF
        while i > 0:
            m += self.tree[i]
            i -= i & -i
        return m

    def update(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

N, K = map(int, input().split())
A = [int(input()) for _ in range(N)]
X = [0]*N
X[0] = A[0]-K
for i in range(1,N):
    X[i] = X[i-1] + A[i] - K

Y = sorted(X)
dic, i = {}, 1
while len(Y):
    y = Y.pop(0)
    dic[y] = i
    if len(Y) >= 1 and Y[0] > y:
        i += 1
Z = list(map(lambda x: dic[x], X))

BIT = Sum_Bit(N)
ans = 0
for i in range(N):
    ans += BIT.get_sum(Z[i])
    if X[i] >= 0: ans += 1
    BIT.update(Z[i], 1)
    
print(ans)


### FIXED CODE ###

class Sum_Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def get_sum(self, i=None):
        if i is None:
            i = self.size
        m = 0  # -INF
        while i > 0:
            m += self.tree[i]
            i -= i & -i
        return m

    def update(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

N, K = map(int, input().split())
A = [int(input()) for _ in range(N)]
X = [0]*N
X[0] = A[0]-K
for i in range(1,N):
    X[i] = X[i-1] + A[i] - K

Y = sorted(set(X))
dic = {y:i+1 for i,y in enumerate(Y)}

BIT = Sum_Bit(N)
ans = 0
for i in range(N):
    ans += BIT.get_sum(dic[X[i]])
    if X[i] >= 0: ans += 1
    BIT.update(dic[X[i]], 1)
    
print(ans)
### BUGGY CODE ###

A,B,C,D = map(int,input().split())

count = 0

for i in range(A,B+1):
    if not i % C == 0:
        if not i % D ==0:
            count += 1

print(count)

### FIXED CODE ###

import math

A,B,C,D = map(int,input().split())

#C,Dの最小公倍数
E = C*D//math.gcd(C,D)
def num_mult(fro,to,mult):
    goal = to//mult
    if fro % mult == 0:
        start = fro // mult
    else:
        start = fro // mult + 1
    
    return goal - start + 1

ans = B-A+1
#Cの倍数
ans -= num_mult(A,B,C)
#Dの倍数
ans -= num_mult(A,B,D)
#C,Dの公倍数
ans += num_mult(A,B,E)

print(ans)
### BUGGY CODE ###

from collections import Counter
N = int(input())
cnt = 0
for i in range(N+1):
    c = Counter(str(i))
    if len(c) == 3 and '7' in c and '5' in c and '3' in c:
        # print(c)
        cnt += 1
print(cnt)


### FIXED CODE ###

from collections import deque
N = int(input())
memo = {i:1 for i in [357, 375, 537, 573, 735, 753]}
ans = 0
queue = deque()
mod = [10**i for i in range(10)]
for key in memo.keys():
  if key <= N:
    ans += 1
    queue.append(key)
while queue:
    key = queue.popleft()
    len_key = len(str(key))
    for i in range(len_key):
        for j in [3,5,7]:
            tmp = (key // mod[i]) * mod[i+1] + j * mod[i] + key % mod[i]
            if tmp not in memo and tmp <= N:
                ans += 1
                memo[tmp] = 1
                queue.append(tmp)
print(ans)
### BUGGY CODE ###

n,m= map(int,input().split())
a = [0]*m
b = [0]*m
for i in range(m):
    a,b = map(int,input().split())
    if i == 0:
        l = [a+j for j in range(b-a+1)]
    l = list(set([a+j for j in range(b-a+1)]) & set(l))
print(len(set(l)))

### FIXED CODE ###

n,m = map(int, input().split())
left = 0
right = 10**5
for _ in range(m):
    l,r = map(int,input().split())
    left = max(left, l)
    right = min(right,r)
print(max(0,right-left+1))
### BUGGY CODE ###

import os, sys, re, math

N = int(input())

#memo = [0 for _ in range(int(2*1e5)+1)]
memo = [0 for _ in range(2*int(1e9)+100)]

for _ in range(N):
	A,B = [int(s) for s in input().split(' ')]
	memo[B] += A

s = 0
flg = True
for i in range(len(memo)):
	s += memo[i]
	if s > i:
		flg = False
		break
if flg:
	print('Yes')
else:
	print('No')


### FIXED CODE ###

import os, sys, re, math

N = int(input())

#memo = [0 for _ in range(int(2*1e5)+1)]
memo = {}

for _ in range(N):
	A,B = [int(s) for s in input().split(' ')]
	if B in memo:
		memo[B] += A
	else:
		memo[B] = A

s = 0
flg = True
key = list(memo.keys())
key = sorted(key)
for i in range(len(key)):
	s += memo[key[i]]
	if s > key[i]:
		flg = False
		break
if flg:
	print('Yes')
else:
	print('No')
### BUGGY CODE ###

from itertools import product
from functools import reduce
# import math

def gcd(a, b):
  while b:
    a, b = b, a % b
  return a
  
def gcd_three(tup):
  return reduce(lambda a, b: gcd(a, b), tup)


K = int(input())
lst = range(1, K+1)
Sum = 0

for tup in product(lst, lst, lst):
  Sum += gcd_three(tup)
  
print(Sum)

### FIXED CODE ###

from math import gcd
k=int(input())
ans=0
for i in range(1,k+1):
    for j in range(1,k+1):
        ans_=gcd(i,j)
        for l in range(1,k+1):
            ans+=gcd(ans_,l)
print(ans)
### BUGGY CODE ###

import sys

input = sys.stdin.readline
n, k = map(int, input().split())
h = list(map(int, input().split()))
dp = [-1] * n
dp[0] = 0
dp[1] = abs(h[0] - h[1])

for i in range(2, n):
    dp[i] = min(abs(h[i] - h[j]) + dp[j] for j in range(max(0, i - k), i))
print(dp[n - 1])


### FIXED CODE ###

import sys


def input():
    return sys.stdin.readline().strip()


def main():
    n, k = map(int, input().split())
    h = list(map(int, input().split()))
    dp = [0] * n
    dp[0] = 0
    dp[1] = abs(h[0] - h[1])

    for i in range(2, n):
        dp[i] = min(abs(h[i] - h[j]) + dp[j] for j in range(max(0, i - k), i))
    print(dp[n - 1])


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

s = input()[::-1]

dp = [0]*2019
dp[0]=1
total = 0
a = 1

for i in list(s):
  total += (int(i)*a)%2019
  dp[total%2019] += 1
  a *= 10
count=0
  
for i in range(2019):
    count += dp[i]*(dp[i]-1)//2
 
print(count)

### FIXED CODE ###

s = input()[::-1]

dp = [0]*2019
dp[0]=1
total = 0
a = 1

for i in list(s):
  total += int(i)*a
  total %= 2019
  dp[total] += 1
  a *= 10
  a %= 2019
count=0
  
for i in range(2019):
    count += dp[i]*(dp[i]-1)//2
 
print(count)
### BUGGY CODE ###

from sys import stdin
import heapq

N, M = [int(x) for x in stdin.readline().rstrip().split()]
B = [[int(x) for x in stdin.readline().rstrip().split()] for _ in range(M)]

graph = [[10 ** 15] * N for _ in range(N)]
for i in range(1, N):
    graph[i][i - 1] = 0
for m in B:
    graph[m[0] - 1][m[1] - 1] = m[2]

d = [(0, 0)]
distance = [10 ** 15] * N
distance[0] = 0
color = ['white'] * N
heapq.heapify(d)

while len(d) > 0:
    temp, u = heapq.heappop(d)
    color[u] = 'black'
    if distance[u] < temp:
        continue
    for v in range(N):
        if color[v] != 'black':
            if distance[u] + graph[u][v] < distance[v]:
                distance[v] = distance[u] + graph[u][v]
                color[v] = 'gray'
                heapq.heappush(d, (distance[v], v))

if distance[N - 1] == 10 ** 15:
    print(-1)
else:
    print(distance[N - 1])

### FIXED CODE ###

from sys import stdin
import heapq

N, M = [int(x) for x in stdin.readline().rstrip().split()]
B = [[int(x) for x in stdin.readline().rstrip().split()] for _ in range(M)]

graph = [[] for _ in range(N)]
for i in range(1, N):
    graph[i].append((0, i - 1))
for m in B:
    graph[m[0] - 1].append((m[2], m[1] - 1))

d = [(0, 0)]
distance = [10 ** 15] * N
distance[0] = 0
color = ['white'] * N
heapq.heapify(d)

while len(d) > 0:
    temp, u = heapq.heappop(d)
    color[u] = 'black'
    if distance[u] < temp:
        continue
    for v in graph[u]:
        if color[v[1]] != 'black':
            if distance[u] + v[0] < distance[v[1]]:
                distance[v[1]] = distance[u] + v[0]
                color[v[1]] = 'gray'
                heapq.heappush(d, (distance[v[1]], v[1]))

if distance[N - 1] == 10 ** 15:
    print(-1)
else:
    print(distance[N - 1])
### BUGGY CODE ###

n,y = map(int,input().split())
if y % 1000 != 0:
    print("-1 -1 -1")
    exit()
dp=[[False]*(y//1000+1) for i in range(n+1)]
dp[0][0] = (0,0,0)

b = y//1000+1
for i in range(1,n+1):
    for j in range(b):
        if dp[i-1][j]:
            h,m,l = dp[i-1][j]
            if j+1 < b:
                dp[i][j+1] = (h,m,l+1)
            if j+5 < b:
                dp[i][j+5] = (h,m+1,l)
            if j+10 < b:
                dp[i][j+10] = (h+1,m,l)
if dp[n][b-1]:
    a,b,c = dp[n][b-1]
    print(a,b,c)
else:
    print("-1 -1 -1")

### FIXED CODE ###

n,y = map(int,input().split())
for i in range(n+1):
    for j in range(n+1-i):
        z = n-i-j
        if 10000*i+5000*j+1000*z == y:
            print(i,j,z)
            exit()
print(-1,-1,-1)
### BUGGY CODE ###

n,m = map(int, input().split())
s = input()

INF=10**10
dp = [[INF,[None]] for _ in range(n+1)]

dp[0]= [0,[]]

import copy
def comp(l1,l2):
    for i in range(len(l1)):
        if l1[i] == l2[i]:
            continue
        return l1[i] < l2[i]
    return True

for i in range(n):
    if dp[i][0] == INF:
        continue
    for j in range(1,m+1):
        if i+j > n:
            break
        if s[i+j] == "1":
            continue
        if dp[i+j][0] > dp[i][0]+1:
            dp[i+j][0] = dp[i][0]+1
            his = copy.deepcopy(dp[i][1])
            his.append(j)
            dp[i+j][1] = his
        elif dp[i+j][0] == dp[i][0]+1:
            his = copy.deepcopy(dp[i][1])
            his.append(j)
            if comp(his,dp[i+j][1]):
                dp[i+j][1] = his

#for tmp in dp:
#    print(tmp)
if dp[-1][0] != INF:
    print(*dp[-1][1])
else:
    print(-1)

### FIXED CODE ###

n,m = map(int, input().split())
s = input()

cnt=0
for i in range(len(s)):
    if s[i]=="1":
        cnt+=1
        if cnt>=m:
            print(-1)
            exit()
    else:
        cnt=0

cnt=0
from collections import defaultdict
d = defaultdict(int)
d[cnt]=n
for i in reversed(range(len(s))):
    if d[cnt] - i > m:
        cnt+=1
    if s[i]=="0":
        d[cnt+1]=i
d[cnt+1]=0

ans=[]
for i in reversed(range(len(d)-1)):
    ans.append(d[i] - d[i+1])
print(*ans,sep=" ")
### BUGGY CODE ###

def cul(lst, m):
    r = 0
    for i in lst:
        r  += i if i < m else m
    return r

n, k = map(int,input().split())
s = input()
val = []

a = 1
for i in range(1, len(s)):
    if s[i-1] == s[i]:
        a += 1
    else:
        val.append(a)
        a = 1
val.append(a)
ans = []
now = int(s[0])
for i in range(len(s)-k):
    ins = 0
    lst = val[i:i+k*2] if now == 0 else val[i:i+k*2+1]
    if len(lst) == 0: break
    ans.append(cul(lst, n))
    now = 1 if now == 0 else 0

print(max(ans) if not len(ans) == 0 else len(s))

### FIXED CODE ###

n, k = map(int,input().split())
s = input()
nums = []

now = 1
cnt = 0
for i in range(len(s)):
    if s[i] == str(now): cnt += 1
    else:
        nums.append(cnt)
        now = 1 - now
        cnt = 1
if not cnt == 0: nums.append(cnt)
if len(nums) % 2 == 0: nums.append(0)

summ = [0]
for i in range(len(nums)):
    summ.append(summ[i]+nums[i])

ans = 0
for i in range(len(nums))[::2]:
    left = i
    right = min(i+k*2+1, len(nums))
    tmp = summ[right] - summ[left]

    ans = max(tmp, ans)


print(ans)
### BUGGY CODE ###

N=int(input())
P=list(map(int, input().split()))

ans=0
for i in range(N):
  flag=True
  for j in range(i):
    if P[i]>P[j]:
      flag=False
      break
  if flag:
    ans+=1
print(ans)

### FIXED CODE ###

N=int(input())
P=list(map(int, input().split()))

ans=1
mi=P[0]
for i in range(1,N):
  if P[i]<=mi:
    ans+=1
    mi=P[i]
print(ans)
### BUGGY CODE ###

def e_bomber():
    from collections import defaultdict
    H, W, M = [int(i) for i in input().split()]
    Bomb = [[int(i) - 1 for i in input().split()] for j in range(M)]

    bomb_row = [0] * H
    bomb_col = [0] * W
    bomb_pos = defaultdict(int)
    for r, c in Bomb:
        bomb_row[r] += 1
        bomb_col[c] += 1
        bomb_pos[(r, c)] += 1

    bomb_row_max = max(bomb_row)
    bomb_col_max = max(bomb_col)

    # 破壊できる数が最大になるような行と列の組を全探索する。
    # (行, 列) が破壊対象の上になってしまわないような組があれば、そこに置けばいい。
    # そのような組がまったくなければ、破壊対象の上に置かざるを得ない (-1 される)。
    flag = False
    for row in [r for r in range(H) if bomb_row_max == bomb_row[r]]:
        for col in [c for c in range(W) if bomb_col_max == bomb_col[c]]:
            if bomb_pos[(row, col)] == 0:
                return bomb_row_max + bomb_col_max
    return bomb_row_max + bomb_col_max - 1

print(e_bomber())

### FIXED CODE ###

def e_bomber():
    import sys
    input = sys.stdin.readline

    H, W, M = [int(i) for i in input().split()]

    bomb_row = [0] * H
    bomb_col = [0] * W
    bomb_pos = set()
    for _ in range(M):
        r, c = [int(i) - 1 for i in input().split()]
        bomb_row[r] += 1
        bomb_col[c] += 1
        bomb_pos.add((r, c))

    bomb_row_max = max(bomb_row)
    bomb_col_max = max(bomb_col)
    row_index_list = [r for r, v in enumerate(bomb_row) if v == bomb_row_max]
    col_index_list = [c for c, v in enumerate(bomb_col) if v == bomb_col_max]

    # 破壊できる数が最大になるような行と列の組を全探索する。
    # (行, 列) が破壊対象の上になってしまわないような組があれば、そこに置けばいい。
    # そのような組がまったくなければ、破壊対象の上に置かざるを得ない (-1 される)。
    for row in row_index_list:
        for col in col_index_list:
            if (row, col) not in bomb_pos:
                return bomb_row_max + bomb_col_max
    return bomb_row_max + bomb_col_max - 1

print(e_bomber())
### BUGGY CODE ###

from collections import deque
from itertools import product
h, w = list(map(int,input().split()))
sy, sx = list(map(int,input().split()))
gy, gx = list(map(int,input().split()))
sx, sy, gx, gy = sx-1, sy-1, gx-1, gy-1
 
G = [list(input()) for _ in range(h)]
D = [[10**6]*w for _ in range(h)]
D[sy][sx] = 0
Q = deque([(sy, sx)])
while Q:
    y, x = Q.pop()
    for dy, dx in product(range(-2, 3), repeat=2):
        ny, nx = y+dy, x+dx
        if dx==dy==0:
            G[y][x] = '#'
            continue
        elif ny<0 or h<=ny or nx<0 or w<=nx:
            continue
        elif G[ny][nx] == '#':
            continue
        elif abs(dy)+abs(dx)<=1:
            G[ny][nx] = '#'
            D[ny][nx] = D[y][x]
            Q.append((ny, nx))
        elif D[ny][nx] == 10**6:
            D[ny][nx] = D[y][x]+1
            Q.appendleft((ny, nx))
            
if D[gy][gx] == 10**6:
    print(-1)
else:
    print(D[gy][gx])


### FIXED CODE ###

from collections import deque
from itertools import product
h, w = list(map(int,input().split()))
sy, sx = list(map(int,input().split()))
gy, gx = list(map(int,input().split()))
sx, sy, gx, gy = sx-1, sy-1, gx-1, gy-1
 
G = [list(input()) for _ in range(h)]
D = [[10**6]*w for _ in range(h)]
D[sy][sx] = 0
Q = deque([(sy, sx)])
while Q:
    y, x = Q.pop()
    for dy, dx in product(range(-2, 3), repeat=2):
        ny, nx = y+dy, x+dx
        if dx==dy==0:
            G[y][x] = '#'
            continue
        elif ny<0 or h<=ny or nx<0 or w<=nx:
            continue
        elif G[ny][nx] == '#':
            continue
        elif abs(dy)+abs(dx)<=1:
            G[ny][nx] = '#'
            D[ny][nx] = D[y][x]
            Q.append((ny, nx))
        elif D[ny][nx] == 10**6:
            D[ny][nx] = D[y][x]+1
            Q.appendleft((ny, nx))
            
if D[gy][gx] == 10**6:
    print(-1)
else:
    print(D[gy][gx])