Problem:


Score : 500 points

Problem Statement

We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).

Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.

Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

Constraints

All values in input are integers.

1 \leq H, W \leq 3 \times 10^5

1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)

1 \leq h_i \leq H

1 \leq w_i \leq W

\left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

Input

Input is given from Standard Input in the following format:

H W M
h_1 w_1
\vdots
h_M w_M

Output

Print the answer.

Sample Input 1

2 3 3
2 2
1 1
1 3

Sample Output 1

3

We can destroy all the targets by placing the bomb at \left(1, 2\right).

Sample Input 2

3 3 4
3 3
3 1
1 1
1 2

Sample Output 2

3

Sample Input 3

5 5 10
2 5
4 3
2 3
5 5
2 2
5 4
5 3
5 1
3 5
1 4

Sample Output 3

6



Sample input:
2 3 3
2 2
1 1
1 3


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
import collections as c

h,w,m = map(int,input().split())
x = []
y = []
z = []
ans = 0
for i in range(m):
    s,t = map(int,input().split())
    x.append(s)
    y.append(t)
    z.append(tuple([s,t]))
a = c.Counter(x)
b = c.Counter(y)

for p,q in a.items():
    for r,s in b.items():
        if tuple([p,r]) in z:
            ans = max(ans,q+s-1)
        else:
            ans = max(ans,q+s)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

H, W, M = map(int, input().split())

bn_h = {}
bn_v = {}

for i in range(M):
    h, w = map(int, input().split())
    bn_h.setdefault(h, set())
    bn_h[h].add(w)
    bn_v.setdefault(w, set())
    bn_v[w].add(h)

b1 = sorted(bn_h.items(), key = lambda x:len(x[1]), reverse=True)
b2 = sorted(bn_v.items(), key = lambda x:len(x[1]), reverse=True)

m1 = len(b1[0][1])
m2 = len(b2[0][1])

max_result = 0
for i in b1:
    h, sh = i
    if len(sh) < m1:
        break
    for j in b2:
        v, sv = j
        if len(sv) < m2:
            break
        result = len(sh) + len(sv) - 1
        if h not in sv:
            result += 1
        max_result = max(max_result, result)
print(max_result)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int, input().split())
h = [0 for i in range(H)]
w = [0 for i in range(W)]
dp = [[0 for i in range(W)] for j in range(H)]

for i in range(M):
    hh, ww = map(int, input().split())
    h[hh - 1] += 1
    w[ww - 1] += 1
    dp[hh - 1][ww - 1] += 1
    

hhh = max(h)
www = max(w)
keep_h = []
keep_w = []

for i in range(H):
    if h[i] == hhh:
        keep_h.append(i)
for i in range(W):
    if w[i] == www:
        keep_w.append(i)

check = 0
for i in keep_h:
    for j in keep_w:
        if dp[i][j] == 0:
            check = 1
print(hhh + www - (1-check))

Submission status: Time Limit Exceeded

Solution code:
h, w, m = map(int, input().split())
h_cnt = [0 for i in range(h)]
w_cnt = [0 for i in range(w)]
bomb_flag = [[False for i in range(w)] for j in range(h)]

for i in range(m):
  _h, _w = map(int, input().split())
  h_cnt[_h - 1] += 1
  w_cnt[_w - 1] += 1
  bomb_flag[_h - 1][_w - 1] = True

h_max = max(h_cnt)
w_max = max(w_cnt)

max_h = []
max_w = []

for i in range(h):
  if h_cnt[i] == h_max:
    max_h.append(i)

for j in range(w):
  if w_cnt[j] == w_max:
    max_w.append(j)

flag = True

for i in max_h:
  for j in max_w:
    if not bomb_flag[i][j]:
      flag = False
      break

print(h_max + w_max - 1 if flag else h_max + w_max)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int, input().split())
hw = [list(map(int, input().split())) for _ in range(M)]

h_value = [0]*(H+1)
w_value = [0]*(W+1)
exist = [ [0 for _ in range(W+1)] for _ in range(H+1)]
for coordinate in hw:
    h_value[coordinate[0]] += 1
    w_value[coordinate[1]] += 1
    exist[coordinate[0]][coordinate[1]] = 1

h_max = max(h_value)
w_max = max(w_value)

h_max_ind = list()
w_max_ind = list()

for i in range(H+1):
    if h_value[i] == h_max:
        h_max_ind.append(i)


for i in range(W+1):
    if w_value[i] == w_max:
        w_max_ind.append(i)

flag = False
for h in h_max_ind:
    for w in w_max_ind:
        if exist[h][w] == 0:
            flag = True

if flag:
    print(h_max + w_max)
else:
    print(h_max + w_max - 1)

Submission status: Time Limit Exceeded

Solution code:
h, w, m = map(int,input().split())
tbl = [[0 for i in range(w)] for j in range(h)]
for i in range(m):
  x, y = map(int,(input().split()))
  tbl[x - 1][y - 1] = 1

def tate(a):
  ans = 0
  for b in range(w):
    x = 0
    for i in range(h):
      if(tbl[i][b] == 1):
        x = x + 1
    if (tbl[a][b] == 1):
      x = x - 1
    if (ans < x):
      ans = x
  return ans

ans = 0
for i in range(h):
  yoko = 0
  for j in range(w):
    if (tbl[i][j] == 1):
      yoko = yoko + 1
  cnt = yoko + tate(i)
  if(cnt > ans):
    ans = cnt
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import collections

h, w, m = map(int, input().split())
hw = [tuple(map(int, input().split())) for _ in range(m)]

hs = []
ws = []
for x, y in hw:
  hs.append(x)
  ws.append(y)
h_cnt = collections.Counter(hs)
w_cnt = collections.Counter(ws)
hs = set(hs)
ws = set(ws)

res = 0
for x in hs:
  for y in ws:
    if res < h_cnt[x]+w_cnt[y]:
      res = h_cnt[x]+w_cnt[y]
      if (x, y) in hw:
        res -= 1
print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
H, W, M = map(int, input().split())
d = defaultdict(int)
tate = [0 for i in range(H+1)]
yoko = [0 for i in range(W+1)]
for i in range(M):
    x, y = map(int, input().split())
    d[(x, y)] = 1
    tate[x] += 1
    yoko[y] += 1

ans = 0
T = []
Y = []
for i, v in enumerate(tate):
    T.append((v, i))
for i, v in enumerate(yoko):
    Y.append((v, i))
T.sort(reverse=True)
Y.sort(reverse=True)

if len(T) == 1 or len(Y) == 1:
    for value, index in T:
        for Value, Index in Y:
            if (index, Index) in d.keys():
                ans = max(ans, value+Value-1)
            else:
                ans = max(ans, value+Value)
    print(ans)

else:
    M = T[0][0]+Y[0][0] - 1
    value_t = T[0][0]
    value_y = Y[0][0]
    for value, index in T:
        if value < value_t:
            break
        for Value, Index in Y:
            if Value < value_y:
                break
            if (index, Index) in d.keys():
                ans = max(ans, value+Value-1)
            else:
                ans = max(ans, value+Value)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter


def main():
    input = sys.stdin.buffer.readline
    h, w, m = map(int, input().split())
    h = [0] * m
    w = [0] * m
    object_set = set()
    for i in range(m):
        h[i], w[i] = map(int, input().split())
        object_set.add((h[i], w[i]))
    h_counter = Counter(h)
    w_counter = Counter(w)
    max_h_num = h_counter.most_common()[0][1]
    max_w_num = w_counter.most_common()[0][1]
    ans = max_h_num + max_w_num

    h_cand = []
    w_cand = []
    for e, n in h_counter.most_common():
        if n == max_h_num:
            h_cand.append(e)
    for e, n in w_counter.most_common():
        if n == max_w_num:
            w_cand.append(e)

    ok = False
    for h_e in h_cand:
        for w_e in w_cand:
            if (h_e, w_e) not in object_set:
                ok = True

    print(ans if ok else ans - 1)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
H,W,M=map(int,input().split())
tgts=set()
for _ in range(M):
    i,j=map(int,input().split())
    tgts.add((i,j))

#print(tgts)

rows=[0]*(H+1)
cols=[0]*(W+1)

for i,j in tgts:
    rows[i]+=1
    cols[j]+=1

ans=0
for i in range(1,H+1):
    for j in range(1,W+1):
        k=rows[i]+cols[j]
        if (i,j) in tgts:
            k-=1
        ans=max(ans,k)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,m = map(int,input().split())
l = [list(map(int,input().split())) for _ in range(m)]
count_h = [0 for i in range(h)]
count_w = [0 for i in range(w)]
bit = list([0 for i in range(w)] for _ in range(h))
for j,k in l:
    count_h[j-1] += 1
    count_w[k-1] += 1
    bit[j-1][k-1] = 1
h_max = max(count_h)
w_max = max(count_w)
h_kouho = []
w_kouho = []
ans = h_max + w_max - 1
for i in range(h):
    if count_h[i]==h_max:
        h_kouho.append(i)
for j in range(w):
    if count_w[j]==w_max:
        w_kouho.append(j)

for i in w_kouho:
    for j in h_kouho:
        if bit[j][i] == 0:
            ans += 1
            print(ans)
            exit()
print(ans)

Submission status: Time Limit Exceeded

Solution code:




def LI():
    return list(map(int,input().split()))
    
def OPEN():
    return map(int,open(0).read().split())
import numpy   
h,w,m=LI()
S=[[0]*w for i in range(h)]
for i in range(m):
    h,w=LI()
    S[h-1][w-1]=1
S=numpy.array(S)
now=0
ind_x=[]
ind_y=[]
Ssumx=[sum(i) for i in S]
SS=S.T
Ssumy=[sum(i) for i in SS]



mx=max(Ssumx)-1
for i,j in enumerate(Ssumx):
    if j>=mx:
        ind_x.append((i,j))
my=max(Ssumy)-1
for i,j in enumerate(Ssumy):
    if j>=my:
        ind_y.append((i,j))
ans=0
for x,numx in ind_x:
    for y,numy in ind_y:
        if S[x][y]==0:
            tmp=numx+numy
        else:
            tmp=numx+numy-1

            
        ans=max(ans,tmp)
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,m = map(int,input().split())
l = [list(map(int,input().split())) for _ in range(m)]
count_h = [0 for i in range(h)]
count_w = [0 for i in range(w)]
bit = list([0 for i in range(w)] for _ in range(h))
for j,k in l:
    count_h[j-1] += 1
    count_w[k-1] += 1
    bit[j-1][k-1] = 1
h_max = max(count_h)
w_max = max(count_w)
h_kouho = []
w_kouho = []
ans = h_max + w_max - 1
for i in range(h):
    if count_h[i]==h_max:
        h_kouho.append(i)
for j in range(w):
    if count_w[j]==w_max:
        w_kouho.append(j)

for i in w_kouho:
    for j in h_kouho:
        if bit[j][i] == 0:
            ans += 1
            print(ans)
            exit()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = list(map(int, input().split())) 
hw = [list(map(int, input().split())) for _ in range(M)]

LH = [0] * H
LW = [0] * W

R = {}
for i in range(M):
  h = hw[i][0] - 1
  w = hw[i][1] - 1
  LH[h] += 1
  LW[w] += 1
  if h in R:
    R[h][w] = 1
  else:
    R[h] = {}
    R[h][w] = 1

mah = max(LH)
maw = max(LW)

ans = mah + maw
for i in range(H):
  if LH[i] != mah: continue
  for j in range(W):
    if LW[j] != maw: continue
    if i not in R:
      break
    if j not in R[i]:
      break
  else:
    continue
  break
else:
  print(ans - 1)
  exit()

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np


def read():
    return sys.stdin.readline().rstrip()


def main():
    h, w, m = map(int, read().split())
    target = [(0, 0) for _ in range(m)]
    row = np.zeros(h, dtype=int)
    col = np.zeros(w, dtype=int)
    for i in range(m):
        hi, wi = [int(i) - 1 for i in input().split()]
        target[i] = (hi, wi)
        row[hi] += 1
        col[wi] += 1
    r = row.max()
    ri = [i for i in range(h) if row[i] == r]
    c = 0
    for rii in ri:
        ci = col.copy()
        for y, x in target:
            if y == rii:
                ci[x] -= 1
        c = max(ci.max(), c)
    ans = r + c
    c = col.max()
    ci = [i for i in range(w) if col[i] == c]
    r = 0
    for cii in ci:
        ri = row.copy()
        for y, x in target:
            if x == cii:
                ri[y] -= 1
        r = max(ri.max(), r)
    ans = max(r + c, ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
H,W,M = map(int, input().strip().split())

squares = []
for i in range(H):
    arr = []
    for j in range(W):
        arr.append(0)
    squares.append(arr)

for i in range(M):
    hi, wi = map(int, input().strip().split())
    squares[hi-1][wi-1] = 1

row_sums = []
for i in range(H):
    row_sums.append(sum(squares[i]))

col_sums = []
for j in range(W):
    sum = 0
    for i in range(H):
        sum += squares[i][j]
    col_sums.append(sum)

max = 0
for i in range(H):
    for j in range(W):
        total = row_sums[i] + col_sums[j]
        if squares[i][j] == 1:
            total -= 1
        if total > max:
            max = total

print(max)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
H, W, M = map(int, input().split())
MASU = [[0 for i in range(W)]for j in range(H)]
hcount = [0]*H
wcount = [0]*W
for i in range(M):
    h, w = map(int, input().split())
    MASU[h-1][w-1] = 1
    hcount[h-1] += 1
    wcount[w-1] += 1

hmax = max(hcount)
wmax = max(wcount)
ans = hmax+wmax
Hkouho = []
Wkouho = []
for i in range(H):
    if hcount[i] == hmax:
        Hkouho.append(i)
for i in range(W):
    if wcount[i] == wmax:
        Wkouho.append(i)
ans -= 1
for i in Hkouho:
    for j in Wkouho:
        if MASU[i][j] == 0:
            ans += 1
            print(ans)
            sys.exit()

print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,n=map(int,input().split())
H=[0]*h
W=[0]*w
L=[0]*n
for i in range(n):
    a,b=map(int,input().split())
    L[i]=(a,b)
    H[a-1]+=1
    W[b-1]+=1
h_max=max(H)
w_max=max(W)
H_max=[i+1 for i, x in enumerate(H) if x == max(H)]
W_max=[i+1 for i, x in enumerate(W) if x == max(W)]

ans=0
for hh in H_max:
    for ww in W_max:
        if (hh,ww) in L:
            ans=max(ans,h_max+w_max-1)
        else:
            ans=h_max+w_max
            break
    else:
        continue
    break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,m=map(int,input().split())
H=[0]*(3*10**5+1)
W=[0]*(3*10**5+1)
M=[]
for i in range(m):
    h,w=map(int,input().split())
    M.append([h,w])
    H[h]+=1
    W[w]+=1

p=max(H)
q=max(W)

X=[i for i in range(3*10**5+1) if H[i]==p]
Y=[i for i in range(3*10**5+1) if W[i]==q]

cnt=1
flag=True
for x in X:
    if flag:
        for y in Y:
            if not [x,y] in M:
                cnt=0
                flag=False
                break

print(p+q-cnt)

Submission status: Time Limit Exceeded

Solution code:
import sys
input =sys.stdin.readline

H,W,M = (int(x) for x in input().rstrip('\n').split())
dh = {}
dw = {}
ds = []
for _ in range(M):
  h,w = (int(x) for x in input().rstrip('\n').split())
  ds.append([h,w])
  if h in dh:
    dh[h] += 1
  else:
    dh[h] = 1
  if w in dw:
    dw[w] += 1
  else:
    dw[w] = 1
mh = max(dh.values())
mw = max(dw.values())
max_h = [k for k,v in dh.items() if v==mh]
max_w = [k for k,v in dw.items() if v==mw]
if any([x,y] not in ds for x in max_h for y in max_w):
  print(mh+mw)
else:
  print(mh+mw-1)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int, input().split())
hk = [[0, i] for i in range(H + 1)]
wk = [[0, j] for j in range(W + 1)]
s = set()
for i in range(M):
    h, w = map(int, input().split())
    hk[h][0] += 1
    wk[w][0] += 1
    s.add((h, w))
hk.sort(reverse=True)
wk.sort(reverse=True)
colmax = wk[0][0]
ans = 0
for lowacc, i in hk:
    if lowacc + colmax < ans:
        break
    for colacc, j in wk:
        ans = max(ans, lowacc + colacc - ((i, j) in s))
        if lowacc + colacc < ans:
            break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int, input().split())
Hsum = [0] * H
Wsum = [0] * W

hw = []
for m in range(M):
  h, w = map(int, input().split())
  Hsum[h-1] += 1
  Wsum[w-1] += 1
  hw.append(str(h)+"_"+str(w))

res = []
for h in range(H):
  for w in range(W):
    if str(h+1)+"_"+str(w+1) in hw:
      res.append(Hsum[h]+Wsum[w]-1)
    else:
      res.append(Hsum[h]+Wsum[w])

print(max(res))

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
import math
import fractions
import bisect
import itertools
from collections import Counter
from collections import deque
from operator import itemgetter
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

h,w,m=mp()
l=[]
x=[]
y=[]
for i in range(m):
    a,b=mp()
    l.append([a,b])
    x.append(a)
    y.append(b)
x=Counter(x)
y=Counter(y)
x=x.most_common()
y=y.most_common()


a=x[0][1]
b=y[0][1]
i=0
px=[]
py=[]
while x[i][1]==a:
    px.append(x[i][0])
    if i==len(x)-1:
        break
    i+=1
i=0
while y[i][1]==b:
    py.append(y[i][0])
    if i==len(y)-1:
        break
    i+=1
for i in px:
    for j in py:
        if not [i,j] in l:
            print(a+b)
            exit()
print(a+b-1)

Submission status: Time Limit Exceeded

Solution code:
H,W,M = map(int,input().split())
X = [0 for i in range(H)]
Y = [0 for j in range(W)]
combi = []
for k in range(M):
    pos = list(map(int,input().split()))
    X[pos[0]-1]+=1
    Y[pos[1]-1]+=1
    combi.append(pos)
a = max(X)
b = max(Y)
X_max = []
Y_max = []
for l in range(H):
    if X[l] == a:
        X_max.append(l+1)
for m in range(W):
    if Y[m] == b:
        Y_max.append(m+1)
flg = 1
for p in X_max:
    for q in Y_max:
        ls = [p,q]
        if not ls in combi:
            flg = 0
            break
print(a + b - flg)

Submission status: Time Limit Exceeded

Solution code:
HK,WK,M = map(int, input().split())
hw_s = [list(map(int, input().split())) for _ in range(M)]
W = {}
H = {}
HW = [[0 for i in range(WK+1)] for _ in range(HK+1)]
for i, hw in enumerate(hw_s):
    h=hw[0]
    w=hw[1]

    if not h in H:
        H[h] = 1
    else:
        H[h] += 1
    
    if not w in W:
        W[w] = 1
    else:
        W[w] += 1

    HW[h][w] = 1
answer = 0
for ki, vi in H.items():
    for kj, vj in W.items():
        answer = max(answer,vi + vj - HW[ki][kj])

print(answer)

Submission status: Time Limit Exceeded

Solution code:
h, w, m = map(int, input().split())
h_cnt = [0 for i in range(h)]
w_cnt = [0 for i in range(w)]
bomb_flag = [[False for i in range(w)] for j in range(h)]

for i in range(m):
  _h, _w = map(int, input().split())
  h_cnt[_h - 1] += 1
  w_cnt[_w - 1] += 1
  bomb_flag[_h - 1][_w - 1] = True

h_max = max(h_cnt)
w_max = max(w_cnt)
flag = True

for i in range(h):
  if not flag:
    break
  if h_cnt[i] != h_max:
    continue
  for j in range(w):
    if w_cnt[j] != w_max:
      continue
    if not bomb_flag[i][j]:
      flag = False
      break

print(h_max + w_max - 1 if flag else h_max + w_max)

Submission status: Time Limit Exceeded

Solution code:

from itertools import product

H, W, M = list(map(int, input().split()))
B = [list(map(int, input().split())) for _ in range(M)]

n = 0
for h, w in product(range(H), range(W)):
	tmp = 0
	for b in B:
		if b[0]-1 == h or b[1]-1 == w:
			tmp += 1
	n = max(n, tmp)

print(n)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
h,w,m=map(int,input().split())

l=np.array([[0]*w for _ in range(h)])

for _ in range(m):
  hm,wm=map(int,input().split())
  a=np.array([[1 if i==hm-1 or j==wm-1 else 0 for j in range(w)] for i in range(h)])
  l+=a
print(l.max())

Submission status: Time Limit Exceeded

Solution code:
"""
    Satwik_Tiwari ;) .
    21st AUGUST , 2020  - FRIDAY
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
@iterative
def dfs(v,visited,st,new):
    new.append(st)
    visited[st] = 1
    for i in v[st]:
        if(visited[i] == 0):
            ok = yield dfs(v,visited,i,new)
    yield True


def solve():
    n,m,p = sep()
    grid = [[0 for i in range(m)] for j in range(n)]

    for i in range(p):
        a,b = sep()
        a-=1
        b-=1
        grid[a][b] +=1

    rowsum = [0]*n
    colsum = [0]*m
    for i in range(n):
        sum = 0
        for j in range(m):
            sum+=grid[i][j]
        rowsum[i] = sum

    for j in range(m):
        sum = 0
        for i in range(n):
            sum+=grid[i][j]
        colsum[j] = sum

    new = [[0 for i in range(m)]for j in range(n)]
    for i in range(n):
        for j in range(m):
            new[i][j] = rowsum[i]+colsum[j]-grid[i][j]

    mx = 0
    for i in range(n):
        for j in range(m):
            mx = max(mx,new[i][j])
    print(mx)




testcase(1)
# testcase(int(inp()))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
h, w, m = map(int, input().split())
data = [list(map(int, input().split())) for _ in range(m)]
field = np.array([[0] * w] * h)
for i in range(m):
    field[data[i][0] - 1, :] += 1
    field[:, data[i][1] - 1] += 1
    field[data[i][0] - 1, data[i][1] - 1] -= 1
print(np.max(field))

Submission status: Time Limit Exceeded

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

h,w,m = ip()
y = [0]*h
x = [0]*w
dt = {}
for i in range(m):
    a,b = ip()
    y[a-1] += 1
    x[b-1] += 1
    dt[(a-1,b-1)] = 1
ans = 0
for i in range(h):
    for j in range(w):
        if dt.get((i,j),0):
            ans = max(ans,y[i]+x[j]-1)
        else:
            ans = max(ans,y[i]+x[j])
print(ans)