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 sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import heapq

def main():
    H, W, M = map(int, readline().split())
    m = map(int,read().split())
    hw = list(zip(m,m))

    bR = [0] * (H+1)
    bC = [0] * (W+1)

    maxes = []
    heapq.heapify([])

    for (h, w) in hw:
        bR[h] += 1
        bC[w] += 1

    rmax = max(bR)
    cmax = max(bC)
    rmis = [i for i in range(H+1) if bR[i] == rmax]
    cmis = [i for i in range(W+1) if bC[i] == cmax]

    ans = rmax + cmax
    minus_flag = True
    for r in rmis:
        for c in cmis:
            if (r, c) not in hw:
                minus_flag = False
                break
    if minus_flag:
        ans -= 1

    
    # print(hw)
    # print(bR, bC)
    # print(rmax, cmax, rmis, cmis)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools

h,w,m = map(int, input().split(" "))
bombs = [[] for i in range(m)]
for i in range(m):
  bombs[i] = tuple(map(int, input().split(" ")))

rows = [bomb[0] for bomb in bombs]
row_count = [[i+1,0] for i in range(h)]
for i in rows:
  row_count[i-1][1] += 1

cols = [bomb[1] for bomb in bombs]
col_count = [[i+1,0] for i in range(w)]
for i in cols:
  col_count[i-1][1] += 1
  
r_max = max([row[1] for row in row_count])
c_max = max([col[1] for col in col_count])

r_options = [row[0] for row in row_count if row[1]==r_max]
c_options = [col[0] for col in col_count if col[1]==c_max]


b_list = list(itertools.product(r_options, c_options))

if all([b in bombs for b in b_list]):
  print(r_max+c_max-1)
else:
  print(r_max+c_max)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import numpy as np


h, w, m = map(int, input().split())

bom_cord = np.empty((m, 2), dtype=int)
h_cnt = np.zeros(h, dtype=int)
w_cnt = np.zeros(w, dtype=int)
bom_cord = set()
for i in range(m):
    hi, wi = map(lambda x: int(x) - 1, input().split())
    bom_cord.add((hi, wi))
    h_cnt[hi] += 1
    w_cnt[wi] += 1

w_max = w_cnt.max()

h_argsort = h_cnt.argsort()[::-1]
w_argsort = w_cnt.argsort()[::-1]

bomber = 0
for hi in h_argsort:
    if h_cnt[hi] + w_max < bomber:
        break
    
    for wi in w_argsort:
        if h_cnt[hi] + w_cnt[wi] < bomber:
            break

        if (hi, wi) in bom_cord:
            bomber = max(bomber, h_cnt[hi] + w_cnt[wi] - 1)
        else:
            bomber = max(bomber, h_cnt[hi] + w_cnt[wi])

print(bomber)

Submission status: Time Limit Exceeded

Solution code:
import sys
input =sys.stdin.readline
from collections import Counter

H,W,M = (int(x) for x in input().rstrip('\n').split())
ds = []
for _ in range(M):
  h,w = (int(x) for x in input().rstrip('\n').split())
  ds.append([h,w])
hs2 = Counter([x[0] for x in ds])
ws2 = Counter([x[1] for x in ds])
max_h=hs2.most_common()[0][1]
max_w=ws2.most_common()[0][1]
mh = [k for k,v in hs2.items() if v==max_h]
mw = [k for k,v in ws2.items() if v==max_w]
hit = [x for x in ds if (x[0] in mh and x[1] in mw)]
if len(hit)<len(mh)*len(mw):
  print(max_h+max_w)
else:
  print(max_h+max_w-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def argmax_poss(xs):
    max_value = max(xs)
    out = []
    for i in range(len(xs)):
        if xs[i] == max_value:
            out.append(i)
    return(out)

h,w,m = map(int,input().split())
Ms = []

h_scores = [0 for i in range(h)]
w_scores = [0 for i in range(w)]

record = deque([])

for i in range(m):
  h,w = map(int,input().split())
  record.append((h-1,w-1))
  h_scores[h-1] += 1
  w_scores[w-1] += 1

max_h_poss = argmax_poss(h_scores)
max_w_poss = argmax_poss(w_scores)

out_pos_count = 0 

while record != deque([]):
    item = record.popleft()
    if item[0] in max_h_poss and item[1] in max_w_poss:
        out_pos_count += 1

if len(max_h_poss) * len(max_w_poss) > out_pos_count:
    print(max(h_scores) + max(w_scores))
else:
    print(max(h_scores) + max(w_scores)-1)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
H,W,M = map(int,input().split())
h_list = [0] * M
w_list = [0] * M
for m in range(M):
    h_list[m],w_list[m] = map(int,input().split())
hh_list = [0] * H
ww_list = [0] * W
for m in range(M):
    hh_list[h_list[m]-1] += 1
for m in range(M):
    ww_list[w_list[m]-1] += 1
h_max = max(hh_list)
w_max = max(ww_list)

h_ans = []
w_ans = []

for hh in range(H):
    if hh_list[hh] == h_max:
        h_ans.append(hh)
for ww in range(W):
    if ww_list[ww] == w_max:
        w_ans.append(ww)
cnt = 0
for i,j in zip(h_list,w_list):
    if i-1 in set(h_ans) and j-1 in set(w_ans):
        cnt += 1
if cnt == len(h_ans) * len(w_ans):
    print(h_max + w_max - 1)
else:
    print(h_max + w_max)

Submission status: Time Limit Exceeded

Solution code:
h,w,m=map(int,input().split())
a=[[] for i in range(m)]
g=[0 for i in range(h)]
r=[0 for i in range(w)]

for i in range(m):
    x,y=map(int,input().split())
    a[i].append(x)
    a[i].append(y)
    g[x-1]+=1
    r[y-1]+=1
G=[]
R=[]
for i in range(h):
    if g[i]==max(g):
        G.append(i+1)
for i in range(w):
    if r[i]==max(r):
        R.append(i+1)
f=0
for i in range(m):
    q=0
    p=0
    x=a[i][0]
    y=a[i][1]
    k=len(G)-1
    l=0
    j=(k+l)//2
    while k-l>1:
        j=(k+l)//2
        if G[j]>=x:
            k=j
        else:
            l=j
    if G[l]==x or G[k]==x:
        p=1

    k = len(R) - 1
    l = 0
    j = (k + l) // 2
    while k - l > 1:
        j = (k + l) // 2
        if R[j] >=y:
            k = j
        else:
            l = j
    if R[l] == y or R[k] == y:
        q = 1

    if p==q==1:
        f+=1
v=1
if f!=len(G)*len(R):
    v=0
ans=max(g)+max(r)
print(ans if v==0 else ans-1)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int, input().split())
Hcount = [0] * (H+1)
Wcount = [0] * (W+1)
target = [[0 for i in range(W+1)] for j in range(H+1)]

for _ in range(M):
    h, w = map(int, input().split())
    Hcount[h] += 1
    Wcount[w] += 1
    target[h][w] = 1

ans = 0
for w in range(1, W+1):
    for h in range(1, H+1):
        # (x,y) に対象物がある場合、二重にカウントしてしまうためtarget[x][y] == 1　を引く。
        tmp = Hcount[h] + Wcount[w] - target[h][w]
        if ans < tmp:
            ans = tmp

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import collections
H,W,M = map(int, input().split())
hw = [map(int, input().split()) for _ in range(M)]
h, w = [list(i) for i in zip(*hw)]

nyuuryoku = [[0] * 2 for i in range(M)]
for i in range(M):
    nyuuryoku[i] = (h[i],w[i])

ch = collections.Counter(h)
cw = collections.Counter(w)
ch_zyunn = ch.most_common()
cw_zyunn = cw.most_common()


result = ch_zyunn[0][1] + cw_zyunn[0][1]
#重複チェックをする
ch_max = [i[0] for i in ch.items() if i[1] >= ch_zyunn[0][1]]
cw_max = [i[0] for i in cw.items() if i[1] >= cw_zyunn[0][1]]

flg = True
for i in range(len(ch_max)):
    for j in range(len(cw_max)):
        if ((ch_max[i],cw_max[j]) in nyuuryoku):
            continue
        else:
          flg = False  
if flg:
    print(result-1)
else:
    print(result)

Submission status: Time Limit Exceeded

Solution code:
h,w,m=map(int,input().rstrip().split())
main=[list(map(int,input().split())) for i in range(m)]
hmax=0
wmax=0
hpoint=[]
wpoint=[]
for i in range(1,h+1):
    count=0
    for j in range(m):
        if i==main[j][0]:
            count+=1
    if count>hmax:
        hpoint.clear()
        hpoint.append(i)
        hmax=count
    elif count==hmax:
        hpoint.append(i)
for i in range(1,w+1):
    count=0
    for j in range(m):
        if i==main[j][1]:
            count+=1
    if count>wmax:
        wpoint.clear()
        wpoint.append(i)
        wmax=count
    elif count==wmax:
        wpoint.append(i)
last=[]
for i in hpoint:
    for j in wpoint:
        last.append([i,j])
flag=0
for i in last:
    mini=0
    for j in main:
        if j==i:
            mini=1
    if mini==0:
        flag=1
        break
if flag==0:
    print(hmax+wmax-1)
else:
    print(hmax+wmax)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import defaultdict 
# from bisect import *
# from heapq import *
# import math
# mod = 10**9+7

H, W, M = map(int, input().split())
raw = defaultdict(int)
col = defaultdict(int)
hw = set()
for i in range(M):
    h, w = map(int, stdin.readline().split())
    raw[h] += 1
    col[w] += 1
    hw.add((h, w))
rawkey = raw.keys()
colkey = col.keys()
ans = 0
for h in rawkey:
    for w in colkey:
        tmp = raw[h] + col[w]
        if (h, w) in hw:
            tmp -= 1
        ans = max(ans, tmp)
print(ans)

Submission status: Time Limit Exceeded

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

Hc = [0 for i in range(H)]
Wc = [0 for i in range(W)]
HW = [[0 for i in range(W)] for i in range(H)]

for m in range(M):
  h, w = map(int, input().split())
  Hc[h - 1] += 1
  Wc[w - 1] += 1
  HW[h - 1][w - 1] = 1
Hcmax = max(Hc)
Hcmax_idx = [i for i, x in enumerate(Hc) if x == Hcmax] 
Wcmax = max(Wc)
Wcmax_idx = [i for i, x in enumerate(Wc) if x == Wcmax] 

ans = Hcmax + Wcmax - 1
f = False
for i in Hcmax_idx:
  for j in Wcmax_idx:
    if HW[i][j] == 0:
      ans = Hcmax + Wcmax
      f = True
      break
  if f:
    break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,m = map(int,input().split())
gyou=[]
retsu=[]
goukei=[]
for i in range(m):
    a,b = map(int,input().split())
    gyou.append(a)
    retsu.append(b)
    goukei.append([a,b])
import collections
gyoucounted = collections.Counter(gyou)
gyoulist = [gyou for gyou,count in gyoucounted.most_common() if count == gyoucounted.most_common()[0][1]]
gkosuu=gyoucounted.most_common()[0][1]


retsucounted = collections.Counter(retsu)
retsulist = [retsu for retsu,count in retsucounted.most_common() if count == retsucounted.most_common()[0][1]]
rkosuu=retsucounted.most_common()[0][1]

judge=0
for i in gyoulist:
    for j in retsulist:
        if [i,j] not in goukei:
            judge=1
            break
if judge==1:
    print(gkosuu+rkosuu)
else:
    print(gkosuu+rkosuu-1)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int,input().split())
Bom = []


listH = [0 for _ in range(H+1)]
listW = [0 for _ in range(W+1)]

for _ in range(M):
    hi, wi = map(int,input().split())
    listH[hi] += 1
    listW[wi] += 1
    Bom.append([hi,wi])

def find_max(listA):
    indexes = []
    max_value = 0
    for i,a in enumerate(listA):
        if max_value < a:
            indexes = [i]
            max_value = a
        elif max_value == a:
            indexes.append(i)
    return indexes

maxH = find_max(listH)
maxW = find_max(listW)

res = 0
for i in maxH:
    for j in maxW:
        temp = 0
        for obj in Bom:
            if obj[0]==i or obj[1]==j:
                temp += 1
        if temp > res:
            res = temp

print(res)

Submission status: Time Limit Exceeded

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

list1 = []
for i in range(M):
    list1.append(list(map(int, input().split())))

listh = [0 for i in range(H+1)]

for k in range(M):
    listh[list1[k][0]]+=1

max1 = 0
loc1 = [0]
for i in range(1, len(listh)):
    if max1 < listh[i]:
        max1 = listh[i]

for i in range(1, len(listh)):
    if max1 == listh[i]:
        loc1.append(i)

#print("Loc1 is ", loc1)
max2_total = 0
for jjj in range(1, len(loc1)):
    listw = [0 for i in range(W+1)]
    #print("jjj is ",jjj)
    for k in range(M):
        if list1[k][0] == loc1[jjj]:
            continue
        listw[list1[k][1]]+=1
    #print("listw is",listw)
    max2 = 0
    loc2 = 0
    for i in range(len(listw)):
        if max2 < listw[i]:
            max2 = listw[i]
            loc2 =  i
    #print("max2 is ",max2)
    if max2_total<max2:
        max2_total = max2

print(max1 + max2_total)

Submission status: Time Limit Exceeded

Solution code:
def main():
    height, width, target_count = [int(x) for x in input().split()]
    count_by_height = [0] * height
    count_by_width = [0] * width
    bomb_is = [[False] * width for _ in range(height)]
    for _ in range(target_count):
        bom_h, bom_w = [int(x) - 1 for x in input().split()]
        count_by_height[bom_h] += 1
        count_by_width[bom_w] += 1
        bomb_is[bom_h][bom_w] = True
        # 最大らしき十字はわかるが，交差点にあるかどうかが不明だ。
        # 最大になりそうな十字がいっぱい（前マスに爆弾，など）だと，
        # 結局 O(H*W) で間に合わなそう。3秒あるけど 10^10 じゃあなあ。
        # DP ぽくはあるが，どう DP を作るかだ。

    # h, w にでいくつ爆破できるか。
    dp = [[0] * width for _ in range(height)]
    dp[0][0] = count_by_height[0] + count_by_width[0] - bomb_is[0][0]
    ans = 0
    for x in range(height):
        for y in range(width):
            now = dp[x][y]
            ans = max(ans, now)
            if x < height - 1:
                if dp[x + 1][y] != 0:
                    continue
                dp[x + 1][y] = (
                    now + count_by_height[x + 1] - count_by_height[x]
                    + bomb_is[x][y] - bomb_is[x + 1][y])
            if y < width - 1:
                if dp[x][y + 1] != 0:
                    continue
                dp[x][y + 1] = (
                    now + count_by_width[y + 1] - count_by_width[y]
                    + bomb_is[x][y] - bomb_is[x][y + 1])
    return ans


if __name__ == '__main__':
    ans = main()
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
from sys import stdin
def main():
    h,w,m= map(int, input().split())
    a = [list(map(int, stdin.readline().split())) for _ in range(m)]
    b=[a[i][0] for i in range(m)]
    c=[a[i][1] for i in range(m)]
    v=Counter(b).most_common()[0][1]
    w=Counter(c).most_common()[0][1]
    i=[j[0] for j in list(Counter(b).items()) if j[1]==v]
    i2=[j[0] for j in list(Counter(c).items()) if j[1]==w]
    l=0
    
    for k in i:
        for t in i2:
            
            if([k,t] in a):
                continue
            else:
                print(v+w)
                l=1
                break
            
        else:
            continue
        break
    if(l==0):
        print(v+w-1)
main()

Submission status: Time Limit Exceeded

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  H,W,M=LI()
  h=[0]*H
  w=[0]*W
  lh=[]
  lw=[]
  d={}
  for _ in range(M):
    a,b=LI()
    lh.append(a)
    lw.append(b)
    a-=1
    b-=1
    h[a]+=1
    w[b]+=1
    d[(a,b)]=1

  ans=0
  for a in lh:
    a-=1
    for b in lw:
      b-=1
      _ans=h[a]+w[b]
      if (a,b) in d:
        _ans-=1
      ans=max(ans,_ans)

  return ans

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int, input().split())
countH = [[h, 0] for h in range(H)]
countW = [[w, 0] for w in range(W)]
Bh = {}

for i in range(M):
  h, w = map(int, input().split())
  h, w = h-1, w-1
  if h in Bh:
    Bh[h].add(w)
  else:
    Bh[h] = {w}
  countH[h][1] += 1
  countW[w][1] += 1

countH.sort(reverse=True, key=lambda x: x[1])
countW.sort(reverse=True, key=lambda x: x[1])
#print(countH)
#print(countW)
#rint(Bh)

maxh = countH[0][1]
maxw = countW[0][1]
ans = maxh + maxw
ch = [countH[0][0]]
i = 1
while i < H and countH[i][1]==maxh:
  ch.append(countH[i][0])
  i += 1
cw = [countW[0][0]]
i = 1
while i < W and countW[i][1]==maxw:
  cw.append(countW[i][0])
  i += 1
flag = False
for h in ch:
  for w in cw:
    #print(h,w)
    if w not in Bh[h]:
      flag = True
if flag:
  print(ans)
else:
  print(ans-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import reduce
from collections import Counter
import time
import datetime
from math import sqrt,gcd

# def time_t():
#     print("Current date and time: " , datetime.datetime.now())
#     print("Current year: ", datetime.date.today().strftime("%Y"))
#     print("Month of year: ", datetime.date.today().strftime("%B"))
#     print("Week number of the year: ", datetime.date.today().strftime("%W"))
#     print("Weekday of the week: ", datetime.date.today().strftime("%w"))
#     print("Day of year: ", datetime.date.today().strftime("%j"))
#     print("Day of the month : ", datetime.date.today().strftime("%d"))
#     print("Day of week: ", datetime.date.today().strftime("%A"))

def ip(): return int(sys.stdin.readline())

def sip(): return sys.stdin.readline()

def mip(): return map(int,sys.stdin.readline().split())

def mips(): return map(str,sys.stdin.readline().split())

def lip(): return list(map(int,sys.stdin.readline().split()))

def matip(n,m):
    lst=[]
    for i in range(n):
        arr = lip()
        lst.append(arr)
    return lst

def factors(n): # find the factors of a number
    return list(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))

def minJumps(arr, n): #to reach from 0 to n-1 in the array in minimum steps
    jumps = [0 for i in range(n)]
    if (n == 0) or (arr[0] == 0):
        return float('inf')
    jumps[0] = 0
    for i in range(1, n):
        jumps[i] = float('inf')
        for j in range(i):
            if (i <= j + arr[j]) and (jumps[j] != float('inf')):
                jumps[i] = min(jumps[i], jumps[j] + 1)
                break
    return jumps[n-1]

def dic(arr): # converting list into dict of count
    return Counter(arr)

def check_prime(n):
    if n<2:
        return False
    for i in range(2,int(n**(0.5))+1,2):
        if n%i==0:
            return False
    return True 

# --------------------------------------------------------- #
# sys.stdin = open('input.txt','r')
# sys.stdout = open('output.txt','w')
# --------------------------------------------------------- #

h,w,m = mip()
x = {}  
y = {}
q = 0
w = 0
final = []
while m:
    m-=1
    l,p = mip()
    final.append([l,p])
    if l not in x:
        x[l] = 1
    else:
        x[l]+=1
    q = max(q,x[l])
    if p not in y:
        y[p] = 1
    else:
        y[p] +=1
    w = max(w,y[p])
lst = []
arr = []
for item in x:
    if x[item]==q:
        lst.append(item)
for item in y:
    if y[item]==w:
        arr.append(item)
flag = 0
for item in lst:
    for kachoda in arr:
        if [item,kachoda] not in final:
            flag = 1
            break
if flag==1:
    print(q+w)
else:
    print(q+w-1)

Submission status: Time Limit Exceeded

Solution code:
def comp(v,w):
    if v[0]<w[0] or (v[0]==w[0] and v[1]<w[1]):
        return True
    else:
        return False


def mergesort(list0):
    n=len(list0)
    if n<=1:
        return list0
    else:
        a=mergesort(list0[0:n//2])
        b=mergesort(list0[n//2:n])
        return merge(a,b)


def merge(list1,list2):
    a=0
    b=0
    s=[]
    for c in range(len(list1)+len(list2)):
        if b>=len(list2) or (a<len(list1) and comp(list1[a],list2[b])):
            s.append(list1[a])
            a=a+1
        else:
            s.append(list2[b])
            b=b+1
    return s


h,w,m=map(int,input().split())
g=[]
e1=[[0,t] for t in range(h)]
e2=[[0,t] for t in range(w)]
for c in range(m):
    a,b=map(int,input().split())
    g.append([a-1,b-1])
    e1[a-1][0]+=1
    e2[b-1][0]+=1
f1=mergesort(e1)
f2=mergesort(e2)
p=f1[-1][0]
q=f2[-1][0]
x=[]
y=[]
for c in range(h-1,-1,-1):
    if p>f1[c][0]:
        break
    x.append(f1[c][1])
for c in range(w-1,-1,-1):
    if q>f2[c][0]:
        break
    y.append(f2[c][1])
r=1
if len(x)*len(y)>m:
    r=0
else:
    for i in x:
        for j in y:
            if not ([i,j] in g):
                r=0
                break
        else:
            continue
        break
print(p+q-r)

Submission status: Time Limit Exceeded

Solution code:
H, W, M = map(int, input().split())
H_max = [0 for _ in range(H+1)]
W_max = [0 for _ in range(W+1)]
A = []
for _ in range(M):
    i, k = map(int, input().split())
    A.append((i,k))
    H_max[i] += 1
    W_max[k] += 1

saidai_H = max(H_max)
possible_H = ([i for i, x in enumerate(H_max) if x == saidai_H])
saidai_W = max(W_max)
possible_W = ([i for i, x in enumerate(W_max) if x == saidai_W])
ans = True
for h in possible_H:
    for w in possible_W:
        if (h, w) in A:
            continue
        else:
            ans = False
            break
if ans:
    print(saidai_H+saidai_W-1)
else:
    print(saidai_H+saidai_W)

Submission status: Time Limit Exceeded

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

cnt_dict_h = {}
cnt_dict_w = {}
bomb_list = []

for i in range(M):
    h, w = [int(i)-1 for i in input().split()]
    bomb_list.append((h,w))
    cnt_dict_h.setdefault(h, 0)
    cnt_dict_h[h] += 1
    cnt_dict_w.setdefault(w, 0)
    cnt_dict_w[w] += 1

max_h_key_list = [kv for kv in cnt_dict_h.items() if kv[1] == max(cnt_dict_h.values())]
max_w_key_list = [kv for kv in cnt_dict_w.items() if kv[1] == max(cnt_dict_w.values())]

count_bombs = []
for h in max_h_key_list:
    for w in max_w_key_list:
        bomb__num = cnt_dict_h[h[0]]+cnt_dict_w[w[0]]
        if(h[0], w[0]) in bomb_list:
            count_bombs.append(bomb__num-1)
        else :
            count_bombs.append(bomb__num)
            
print(max(count_bombs))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
input = stdin.readline
from collections import defaultdict, deque
h, w, m = map(int,input().split())
row = defaultdict(int)
col = defaultdict(int)
grid = defaultdict(int)
for _ in range(m):
    x,y = map(int,input().split())
    row[x]+=1
    col[y]+=1
    grid[(x,y)]=1


row = sorted(list(row.items()), key = lambda x: x[1], reverse = True)
col = sorted(list(col.items()), key = lambda x: x[1], reverse = True)
i,j = 0,0
ans = row[0][1]+col[0][1] + (-1 if grid[(row[0][0], col[0][0])] else 0)
dq = deque([(i,j)])
while dq:
    i,j = dq.popleft()
    temp = row[i][1]+col[j][1] + (-1 if grid[(row[i][0], col[j][0])] else 0)
    if ans<temp:
        ans = temp
        break
    
    if i+1<len(row):dq.append((i+1,j))
    if j+1<len(col):dq.append((i,j+1))

    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,m,k=map(int,input().split())
l=[0]*n
d=[0]*m
p=[]
for i in range(n):
    t=[]
    for j in range(m):
        t.append(0)
    p.append(t)
for u in range(k):
    x,y=map(int,input().split())
    l[x-1]+=1
    d[y-1]+=1
    p[x-1][y-1]=1
x=max(l)
y=max(d)
xx,yy=[],[]
for i in range(n):
    if(l[i]==x):
        xx.append(i)
for j in range(m):
    if(d[j]==y):
        yy.append(j)
f=0
for i in range(len(xx)):
    for j in range(len(yy)):
        if(p[xx[i]][yy[j]]==0):
            f=1
            break
if(f==0):
    print(x+y-1)
else:
    print(x+y)

Submission status: Time Limit Exceeded

Solution code:
h,w,m = map(int,input().split())
gyou = [0]*h
retu = [0]*w
zahyo = []
kiroku = []
for i in range(m):
    zahyo = list(map(int,input().split()))
    kiroku.append(zahyo)
    gyou[zahyo[0]-1] += 1
    retu[zahyo[1]-1] += 1
answer = 0
counter = 0
for i in range(h):
    for j in range(w):
        counter = gyou[i]
        counter += retu[j]
        if counter > answer:
            if [i+1,j+1] in kiroku:
                if counter-1 > answer:
                    answer = counter-1
            else:
                answer = counter
print(answer)

Submission status: Time Limit Exceeded

Solution code:
import collections

H,W,M = map(int, input().split())
h = [0]*M
w = [0]*M
for i in range(M):
    h[i], w[i] = map(int, input().split())
ch = collections.Counter(h).most_common()
mh = [ch[0][0]]
mnh = ch[0][1]
for i in range(1,len(ch)):
    if mnh == ch[i][1]:
        mh.append(ch[i][0])
        continue
    else:
        break
    break
cw = collections.Counter(w).most_common()
mw = [cw[0][0]]
mnw = cw[0][1]
for i in range(1,len(cw)):
    if mnw == cw[i][1]:
        mw.append(cw[i][0])
        continue
    else:
        break
    break
for h1 in mh:
    for w1 in mw:
        if (h1,w1) not in zip(h,w):
            print(mnh+mnw)
            exit()
print(mnh+mnw-1)

Submission status: Time Limit Exceeded

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def MAP1()  : return map(lambda x:int(x)-1,input().split())
def LIST()  : return list(MAP())
def LIST1() : return list(MAP1())

def solve():
    h, w, m = MAP()
    s = [LIST1() for i in range(m)]
    ay = [0]*h
    ax = [0]*w
    c = [[0]*w for i in range(h)]
    for x in s:
        ay[x[0]] += 1
        ax[x[1]] += 1
        c[x[0]][x[1]] = 1

    my = max(ay)
    mx = max(ax)
    by = [i for i, x in enumerate(ay) if x == my]
    bx = [i for i, x in enumerate(ax) if x == mx]

    ans = my + mx
    tmp = 1
    for y in by:
        for x in bx:
            if c[y][x] == 0:
               tmp = 0
    print(ans - tmp)

if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def main():
    H, W, M = map(int, input().split())
    bomb = set()
    yoko = [0] * W
    tate = [0] * H
    for _ in range(M):
        h, w = map(int, input().split())
        bomb.add((h-1, w-1))
        yoko[w - 1] += 1
        tate[h - 1] += 1

    idx_yoko = [(yoko[i], i) for i in range(W)]
    idx_tate = [(tate[i], i) for i in range(H)]
    idx_yoko.sort(reverse=True, key=lambda x: (x[0], x[1]))
    idx_tate.sort(reverse=True, key=lambda x: (x[0], x[1]))
    ans = 0
    for p in range(min(5000, W)):
        for q in range(min(5000, H)):
            yoko_bomb, idx_w = idx_yoko[p]
            tate_bomb, idx_h = idx_tate[q]
            get_bomb = yoko_bomb + tate_bomb
            if (idx_h, idx_w) in bomb: get_bomb -= 1
            ans = max(ans, get_bomb)
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import collections
import numpy as np
import sys
h,w,m = (int(x) for x in input().split())
hw = [[int(x) for x in input().split()] for _ in range(m)]

np_hw = np.array(hw)

c_h = collections.Counter(np_hw[:,0])
c_w = collections.Counter(np_hw[:,1])

max_h_list = []
max_w_list = []
for i in range(len(c_h)):
    if c_h.most_common()[i][1] == c_h.most_common()[0][1]:
        max_h_list.append(c_h.most_common()[i][0])
    else:
        break
for i in range(len(c_w)):
    if c_w.most_common()[i][1] == c_w.most_common()[0][1]:
        max_w_list.append(c_w.most_common()[i][0])
    else:
        break

ans = c_h.most_common()[0][1]+c_w.most_common()[0][1]-1
for i in max_h_list:
    for j in max_w_list:
        if [i,j] not in hw:
            ans += 1
            print(ans)
            sys.exit()

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#from functools import lru_cache
import sys
from itertools import product,combinations
from functools import reduce,lru_cache
import heapq

def vfunc(f): return lambda *lst, **kwargs: list(map(lambda *x:f(*x,**kwargs),*lst))

def list_t(l): return vfunc(lambda *args:args)(*l)

def rvfunc(f): return lambda *lst, **kwargs: list(map(lambda *x:rvfunc(f)(*x,**kwargs) if all(vfunc(lambda y:isinstance(y,list))(x)) else f(*x,**kwargs),*lst))

def reader():return vfunc(lambda l:l.split())(sys.stdin.readlines())

s=rvfunc(int)(reader())
h,w,m=s[0]
hl,wl = [0]*h,[0]*w
hw=s[1:]
hh,ww = list_t(hw)
for i in range(len(hw)):
    hl[hh[i]-1]+=1
    wl[ww[i]-1]+=1
hlmax,wlmax = vfunc(max)([hl,wl])
hlidx = tuple(filter(lambda a:hl[a]==hlmax,range(len(hl))))
wlidx = tuple(filter(lambda a:wl[a]==wlmax,range(len(wl))))
minus = 1
fltd = tuple(filter(lambda a:a[0]-1 in hlidx and a[1]-1 in wlidx,hw))
if len(fltd)!=len(hlidx)*len(wlidx): minus=0
#print(fltd,hw)
# for i in hlidx:
#     for j in wlidx:
# #        print([i+1,j+1],fltd)
#         if not [i+1,j+1] in fltd:
#             minus=0
#             break
print(max(hl)+max(wl)-minus)