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: Accepted

Solution code:
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
#setrecursionlimit(300000)
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
#sys.setrecursionlimit(300000)
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")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")


# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)


# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]


class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD


# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m


# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z


# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por


# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] < key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count


# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c
def binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)


# --------------------------------------------------binary------------------------------------
class BinaryTrie:
    class Node:
        def __init__(self, bit: bool = False):
            self.bit = bit  # Stores the current bit (False if 0, True if 1)
            self.children = []
            self.count = 0  # stores number of keys finishing at this bit
            self.counter = 1  # stores number of keys with this bit as prefix

    def __init__(self, size):
        self.root = BinaryTrie.Node()
        self.size = size  # Maximum size of each key

    def convert(self, key):
        """Converts key from string/integer to a list of boolean values!"""
        bits = []
        if isinstance(key, int):
            key = bin(key)[2:]
        if isinstance(key, str):
            for i in range(self.size - len(key)):
                bits += [False]
            for i in key:
                if i == "0":
                    bits += [False]
                else:
                    bits += [True]
        else:
            return list(key)
        return bits

    def add(self, key):
        """Add a key to the trie!"""
        node = self.root
        bits = self.convert(key)
        for bit in bits:
            found_in_child = False
            for child in node.children:
                if child.bit == bit:
                    child.counter += 1
                    node = child
                    found_in_child = True
                    break
            if not found_in_child:
                new_node = BinaryTrie.Node(bit)
                node.children.append(new_node)
                node = new_node
        node.count += 1

    def remove(self, key):
        """Removes a key from the trie! If there are multiple occurences, it removes only one of them."""
        node = self.root
        bits = self.convert(key)
        nodelist = [node]
        for bit in bits:
            for child in node.children:
                if child.bit == bit:
                    node = child
                    node.counter -= 1
                    nodelist.append(node)
                    break
        node.count -= 1
        if not node.children and not node.count:
            for i in range(len(nodelist) - 2, -1, -1):
                nodelist[i].children.remove(nodelist[i + 1])
                if nodelist[i].children or nodelist[i].count:
                    break

    def query(self, prefix, root=None):
        """Search for a prefix in the trie! Returns the node if found, otherwise 0."""
        if not root: root = self.root
        node = root
        if not root.children:
            return 0
        for bit in prefix:
            bit_not_found = True
            for child in node.children:
                if child.bit == bit:
                    bit_not_found = False
                    node = child
                    break
            if bit_not_found:
                return 0
        return node
#--------------------------------------------trie-------------------------------------------------
class TrieNode:

    # Trie node class
    def __init__(self):
        self.children = [None] * 26
        self.data=0
        self.isEndOfWord = False


class Trie:

    # Trie data structure class
    def __init__(self):
        self.root = self.getNode()

    def getNode(self):

        # Returns new trie node (initialized to NULLs)
        return TrieNode()

    def _charToIndex(self, ch):

        # private helper function
        # Converts key current character into index
        # use only 'a' through 'z' and lower case

        return ord(ch) - ord('a')

    def insert(self, key,val):
        pCrawl = self.root
        length = len(key)
        for level in range(length):
            index = self._charToIndex(key[level])

            # if current character is not present
            if not pCrawl.children[index]:
                pCrawl.children[index] = self.getNode()
            pCrawl = pCrawl.children[index]
            pCrawl.data+=val
        pCrawl.isEndOfWord = True

    def search(self, key):

        # Search key in the trie
        # Returns true if key presents
        # in trie, else false
        pCrawl = self.root
        length = len(key)
        c=0
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                return False
            pCrawl = pCrawl.children[index]
        return pCrawl!=None
    def present(self, key):
        ans=0
        pCrawl = self.root
        length = len(key)
        c=0
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                return False
            pCrawl = pCrawl.children[index]
            ans+=pCrawl.data
        if pCrawl!=None:
            return ans
        return -1
#----------------------------------trie----------------------------
h,w,m=map(int,input().split())
d=defaultdict(int)
d1=defaultdict(int)
tot=set()
for i in range(m):
    a,b=map(int,input().split())
    d[a]+=1
    d1[b]+=1
    tot.add((a,b))
m=max(d.values())
m1=max(d1.values())
s=set()
s1=set()
for i in d:
    if d[i]==m:
        s.add(i)
for i in d1:
    if d1[i]==m1:
        s1.add(i)
c=set()
for i in tot:
    if i[0] in s and i[1] in s1:
        c.add(i)
#print(m,m1,c,s,s1)
if len(c)==len(s)*len(s1):
    print(m+m1-1)
else:
    print(m+m1)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(500005)
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().strip()

h, w, m = na()
rs = [0] * h
cs = [0] * w

se = set()
for i in range(m):
    r, c = na()
    rs[r-1] += 1
    cs[c-1] += 1
    se.add((r-1)*w+c-1)

rmax = max(rs)
cmax = max(cs)

remax = rs.count(rmax)
cemax = cs.count(cmax)
if remax * cemax > m:
    print(rmax + cmax)
    sys.exit(0)

rmaxs = [i for i, _ in enumerate(rs) if _ == rmax]
cmaxs = [i for i, _ in enumerate(cs) if _ == cmax]
for r in rmaxs:
    for c in cmaxs:
        if r*w+c not in se:
            print(rmax + cmax)
            sys.exit(0)
print(rmax + cmax - 1)

Submission status: Accepted

Solution code:
import collections
import sys
import math
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())
def NIJIGEN(H): return [list(input()) for i in range(H)]
H,W,M=map(int,input().split())
A=list()
B=list()
for i in range(M):
  a,b=map(int,input().split())
  A.append(a)
  B.append(b)
c = collections.Counter(A)
s=c.most_common()
k=s[0][0]
t=s[0][1]
L=list()
for i in range(M):
  if A[i]!=k:
    L.append(B[i])
c = collections.Counter(L)
s=c.most_common()
if len(s)!=0:
  ans=s[0][1]+t
else:
  ans=t
c = collections.Counter(B)
s=c.most_common()
k=s[0][0]
t=s[0][1]
L=list()
for i in range(M):
  if B[i]!=k:
    L.append(A[i])
c = collections.Counter(L)
s=c.most_common()
if len(s)!=0:
  q=s[0][1]+t
else:
  q=t
ans=max(ans,q)
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

H, W, m = map(int, input().split())
h_s = [0 for _ in range(H)]
w_s = [0 for _ in range(W)]
dd = defaultdict(bool)
for _ in range(m):
    h, w = map(int, input().split())
    h_s[h - 1] += 1
    w_s[w - 1] += 1
    dd[str(h - 1) + "-" + str(w - 1)] = True

max_h = max(h_s)
max_w = max(w_s)
hh = []
ww = []
for i, h in enumerate(h_s):
    if h == max_h:
        hh.append(i)
for i, w in enumerate(w_s):
    if w == max_w:
        ww.append(i)
ans = max_h + max_w - 1
for h in hh:
    for w in ww:
        if not dd[str(h) + "-" + str(w)]:
            print(ans + 1)
            exit()
print(ans)

Submission status: Runtime Error

Solution code:
import sys
h,w,m = map(int,input().split())
h_lst = [[0,i] for i in range(h)]
w_lst = [[0,i] for i in range(w)]
memo = []

for i in range(m):
  x,y = map(int,input().split())
  h_lst[x-1][0] += 1
  w_lst[y-1][0] += 1
  memo.append((x-1,y-1))

h_lst.sort(reverse = True)
w_lst.sort(reverse = True)
Max_h = h_lst[0][0]
Max_w = w_lst[0][0]
h_ans = [h_lst[0][1]]
w_ans = [w_lst[0][1]]
if h != 1:
  s = 1
  while h_lst[s][0] == Max_h:
    h_ans.append(h_lst[s][1])
    s+= 1  
if w!= 1:  
  t=1  
  while w_lst[t][0] == Max_w:
    w_ans.append(w_lst[t][1])
    t += 1
  

memo = set(memo)

#探索するリストは、最大を取るものの集合でなければ計算量はO(m)にはならない！             
for j in h_ans:
  for k in w_ans:
    if (j,k) not in memo:
      print(Max_h+Max_w)
      sys.exit()
print((Max_h+Max_w)-1)

Submission status: Runtime Error

Solution code:
import sys
h,w,m = map(int,input().split())
h_lst = [[0,i] for i in range(h)]
w_lst = [[0,i] for i in range(w)]
memo = []

for i in range(m):
  x,y = map(int,input().split())
  h_lst[x-1][0] += 1
  w_lst[y-1][0] += 1
  memo.append((x-1,y-1))

h_lst.sort(reverse = True)
w_lst.sort(reverse = True)
Max_h = h_lst[0][0]
Max_w = w_lst[0][0]
h_ans = [h_lst[0][1]]
w_ans = [w_lst[0][1]]
s = 1
while h_lst[s][0] == Max_h:
  h_ans.append(h_lst[s][1])
  s+= 1   
t=1  
while w_lst[t][0] == Max_w:
  w_ans.append(w_lst[t][1])
  t += 1
  

memo = set(memo)

#探索するリストは、最大を取るものの集合でなければ計算量はO(m)にはならない！             
for j in h_ans:
  for k in w_ans:
    if (j,k) not in memo:
      print(Max_h+Max_w)
      sys.exit()
print((Max_h+Max_w)-1)

Submission status: Runtime Error

Solution code:
import sys
h,w,m = map(int,input().split())
h_lst = [[0,i] for i in range(h)]
w_lst = [[0,i] for i in range(w)]
memo = []

for i in range(m):
  x,y = map(int,input().split())
  h_lst[x-1][0] += 1
  w_lst[y-1][0] += 1
  memo.append((x-1,y-1))

h_lst.sort(reverse = True)
w_lst.sort(reverse = True)
Max_h = h_lst[0][0]
Max_w = w_lst[0][0]
h_ans = [h_lst[0]]
w_ans = [w_lst[0]]
s = 1
while h_lst[s][0] == Max_h:
  h_ans.append(h_lst[s])
  s+= 1   
t=1  
while w_lst[t][0] == Max_w:
  w_ans.append(w_lst[t])
  t += 1
  

memo = set(memo)

#探索するリストは、最大を取るものの集合でなければ計算量はO(m)にはならない！             
for [y,j] in h_ans:
  if y == Max_h:
    for [z,k] in w_ans:
      if (j,k) not in memo and w_lst[0][0] == z:
        print(Max_h+w_lst[0][0])
        sys.exit()
print((Max_h+w_lst[0][0])-1)

Submission status: Runtime Error

Solution code:
import sys
h,w,m = map(int,input().split())
h_lst = [0]*h
w_lst = [0]*w
memo = []

for i in range(m):
  x,y = map(int,input().split())
  h_lst[x-1] += 1
  w_lst[y-1] += 1
  memo.append((x-1,y-1))

sh = 0
for i in range(h):
  if h_lst[i] > sh:
    sh = h_lst[i]
sw = 0
for i in range(h):
  if h_lst[i] > sw:
    sw = w_lst[i]



memo = set(memo)
              

for i in range(h):
  if h_lst[i] == sh:
    for j in range(w):
      if (i,j) not in memo and w_lst[j] == sw:
        print(sh+sw)
        sys.exit()
print((sh+sw)-1)

Submission status: Runtime Error

Solution code:
H,W,M=list(map(int,input().split()))
bomb=[]
import sys
sys.setrecursionlimit(10**7)
for i in range(M):
    bomb.append(list(map(int,input().split())))
import numpy as np
rows=np.zeros(H+1)
columns=np.zeros(W+1)
for i in range(M):
    rows[bomb[i][0]]+=1
    columns[bomb[i][1]]+=1

maxrows=0
rowi=[]
columni=[]
maxcolumns=0
for i in range(M):
    if maxrows<rows[bomb[i][0]]:
        rowi=[i]
        maxrows=rows[bomb[i][0]]
    elif maxrows==rows[bomb[i][0]] and maxrows!=0:
        rowi.append(i)
for i in range(M):
    if maxcolumns<columns[bomb[i][0]]:
        columni=[i]
        maxcolumns=columns[bomb[i][0]]
    elif maxcolumns==columns[bomb[i][0]] and maxcolumns!=0:
        columni.append(i)

def total(rowi,columni):
    for i in rowi:
        if i not in columni:
            print(maxrows+maxcolumns)
            return
    for i in columni:
        if i not in rowi:
            print(maxrows+maxcolumns)
            return
    print(maxrows+maxcolumns-1)
    return
total(rowi,columni)

Submission status: Runtime Error

Solution code:
H,W,M=list(map(int,input().split()))
bomb=[]
import sys
sys.setrecursionlimit(10**7)
for i in range(M):
    bomb.append(list(map(int,input().split())))
import numpy as np

total=np.zeros([H,W])
for i in range(M):
    total[bomb[i][0]-1][bomb[i][1]-1]-=1
    for j in range(H):
        total[j][bomb[i][1]-1]+=1
    for j in range(W):
        total[bomb[i][0]-1][j]+=1
        
print(max(max(total[i][j] for i in range(H)) for j in range(W)))

Submission status: Runtime Error

Solution code:
H,W,M=list(map(int,input().split()))
bomb=[]
import sys
sys.setrecursionlimit(10**7)
for i in range(M):
    bomb.append(list(map(int,input().split())))
import numpy as np
row=np.zeros(H)
column=np.zeros(W)
X=np.zeros([H,W])
total=np.zeros([H,W])
for i in range(M):
    X[bomb[i][0]-1][bomb[i][1]-1]+=1
for j in range(H):
    row[j]=sum(X[j][k] for k in range(W))
for j in range(W):
    column[j]=sum(X[k][j] for k in range(H))
for i in range(H):
    for j in range(W):
        total[i][j]=row[i]+column[j]-X[i][j]
        
print(max(max(total[i][j] for i in range(H)) for j in range(W)))

Submission status: Runtime Error

Solution code:
H,W,M=list(map(int,input().split()))
bomb=[]
for i in range(M):
    bomb.append(list(map(int,input().split())))
import numpy as np
row=np.zeros(H)
column=np.zeros(W)
X=np.zeros([H,W])
total=np.zeros([H,W])
for i in range(M):
    X[bomb[i][0]-1][bomb[i][1]-1]+=1
for j in range(H):
    row[j]=sum(X[j][k] for k in range(W))
for j in range(W):
    column[j]=sum(X[k][j] for k in range(H))
for i in range(H):
    for j in range(W):
        total[i][j]=row[i]+column[j]-X[i][j]
        
print(max(max(total[i][j] for i in range(H)) for j in range(W)))

Submission status: Runtime Error

Solution code:
H,W,M=list(map(int,input().split()))
bomb=[]
for i in range(M):
    bomb.append(list(map(int,input().split())))
import numpy as np
row=np.zeros(H)
column=np.zeros(W)
X=np.zeros([H,W])
total=np.zeros([H,W])
for i in range(M):
    X[bomb[i][0]-1][bomb[i][1]-1]=1
for j in range(H):
    row[j]=sum(X[j][k] for k in range(W))
for j in range(W):
    column[j]=sum(X[k][j] for k in range(H))
for i in range(H):
    for j in range(W):
        total[i][j]=row[i]+column[j]-X[i][j]
        
print(max(max(total[i][j] for i in range(H)) for j in range(W)))

Submission status: Runtime Error

Solution code:
from sys import stdin,exit
import collections

input = stdin.readline

Y, X, M = map(int, input().split())
bomb = set([tuple(map(int,inp.split())) for inp in stdin.read().splitlines()])
cx = collections.defaultdict(int)
cy = collections.defaultdict(int)
for y,x in bomb:
    cx[x] += 1
    cy[y] += 1
mx = max(cx.values())
my = max(cy.values())
candidateX = [x for (x,v) in cx.items() if v == mx]
candidateY = [y for (y,v) in cy.items() if v == my]
res = mx + my -1
for x in candidateX:
    for y in candidateY:
        if (y,x) not in bomb:
            print(res + 1)
            exit(1)

print(res)

Submission status: Runtime Error

Solution code:

# SHREE RAM

import os,sys
from io import BytesIO, IOBase
from collections import defaultdict


def main():
    h,w,m= map(int,input().split())
    x=defaultdict(lambda :0)
    y=defaultdict(lambda :0)
    for i in range(int(input())):
        a,b=map(int,input().split())

        x[a]+=1
        t=-1
        y[b]+=1
    for i in x:
        if x[i]>t:
            t=x[i]
         
    for i in y:
        if y[i]>t:
            m2=y[i]
   
    print(t+m2)


#Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import numpy as np

H, W, M = map(int, input().split())
map_ = np.zeros((H, W), dtype=np.bool)

h_sum = [0] * H
w_sum = [0] * W

for _ in range(M):
    h, w = map(int, input().split())
    map_[h-1, w-1] = 1
    h_sum[h-1] += 1
    w_sum[w-1] += 1

h_max = max(h_sum)
w_max = max(w_sum)

h_argmax = set()
w_argmax = set()

for i, h in enumerate(h_sum):
    if h == h_max:
        h_argmax.add(i) 

for i, w in enumerate(w_sum):
    if w == w_max:
        w_argmax.add(i)

ans = h_max + w_max

for h in h_argmax:
    for w in w_argmax:
        if map_[h, w] == 0:
            print(ans)
            exit()
print(ans - 1)

Submission status: Runtime Error

Solution code:
import numpy as np

H, W, M = map(int, input().split())
map_ = np.zeros((H, W), dtype=np.uint8)

h_sum = [0] * H
w_sum = [0] * W

Submission status: Runtime Error

Solution code:
# import numpy as np

H, W, M = map(int, input().split())
# map_ = np.zeros((H, W), dtype=np.uint8)
map_ = [[0] * W for _ in range(H)]

h_sum = [0] * H
w_sum = [0] * W

for _ in range(M):
    h, w = map(int, input().split())
    map_[h-1, w-1] = 1
    h_sum[h-1] += 1
    w_sum[w-1] += 1

h_max = max(h_sum)
w_max = max(w_sum)

h_argmax = set()
w_argmax = set()

for i, h in enumerate(h_sum):
    if h == h_max:
        h_argmax.add(i) 

for i, w in enumerate(w_sum):
    if w == w_max:
        w_argmax.add(i)

ans = h_max + w_max

for h in h_argmax:
    for w in w_argmax:
        if map_[h, w] == 0:
            print(ans)
            exit()
print(ans - 1)

Submission status: Runtime Error

Solution code:
import numpy as np

H, W, M = map(int, input().split())
map_ = np.zeros((H, W), dtype=np.uint8)

h_sum = [0] * H
w_sum = [0] * W

for _ in range(M):
    h, w = map(int, input().split())
    map_[h-1, w-1] = 1
    h_sum[h-1] += 1
    w_sum[w-1] += 1

ans = 0
h_max = max(h_sum)
w_max = max(w_sum)

h_argmax = set()
w_argmax = set()

for i, h in enumerate(h_sum):
    if h == h_max:
        h_argmax.add(i) 

for i, w in enumerate(w_sum):
    if w == w_max:
        w_argmax.add(i)

ans = h_max + w_max

for h in h_argmax:
    for w in w_argmax:
        if map_[h, w] == 0:
            print(ans)
            exit()
print(ans - 1)

Submission status: Runtime Error

Solution code:
import numpy as np

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

for _ in range(M):
    h, w = map(int, input().split())
    map_[h-1, w-1] = 1

sum_h = np.sum(map_, axis=1)
sum_w = np.sum(map_, axis=0)
ans = 0

for h in range(H):
    for w in range(W):
        ans = max(sum_h[h] + sum_w[w] - map_[h, w], ans)

print(int(ans))

Submission status: Runtime Error

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from math import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
INF = float('inf')
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
    return int(readline())
H,W,M = readInts()
bomb = [[0] * W for _ in range(H)]
for i in range(M):
    h,w = map(lambda x:int(x)-1,input().split())
    bomb[h][w] = 1
clean = [[0] * W for _ in range(H)]
# H を決める
for h in range(H):
    v = 0
    for w in range(W):
        if bomb[h][w] == 1:
            v += 1
    for w in range(W):
        clean[h][w] += v
# W を決める
for w in range(W):
    v = 0
    for h in range(H):
        if bomb[h][w] == 1:
            v += 1
    for h in range(H):
        clean[h][w] += v
# print(*clean,sep='\n')
# 答え
ans = 0
for h in range(H):
    for w in range(W):
        if bomb[h][w] == 1:
            ans = max(ans, clean[h][w]-1)
        else:
            ans = max(ans,clean[h][w])
print(ans)

Submission status: Runtime Error

Solution code:
h,w,m=map(int,input().split())
t=[0]*(w*h)
nh=[0]*h
nw=[0]*w
for i in range(m):
    hi,wi=map(int,input().split())
    t[(hi-1)*h+(wi-1)]=1
    nh[hi-1]=nh[hi-1]+1
    nw[wi-1]=nw[wi-1]+1

hIdx=[i for i, v in enumerate(nh) if v == max(nh)]
wIdx=[i for i, v in enumerate(nw) if v == max(nw)]


nMax=max(nh)+max(nw)-1
for hh in hIdx:
    for ww in wIdx:
        if t[hh*h+ww]==0:
            nMax=nMax+1
            break
    else:
        continue
    break

print(nMax)

Submission status: Runtime Error

Solution code:
h, w, m = map(int, input().split())
grid = [[0] * w for i in range(h)]
#bombs = []
#集計
sum_yoko = [0] * h
sum_tate = [0] * w

for bomb in range(m):
    y, x = map(int, input().split())
    grid[y-1][x-1] = 1
    sum_yoko[y-1] += 1
    sum_tate[x-1] += 1

saidai = 0
for i in range(h):
    for j in range(w):
        now = sum_yoko[i] + sum_tate[j]
        #重なった判定
        if grid[i][j] == 1:
            now -= 1;
        saidai = max(saidai, now) 

print(saidai)