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:

H, W, M = map(int,input().split())
h_count = [0] * (H+1)
w_count = [0] * (W+1)
memo = set()

for _ in range(M):
    h, w = map(int,input().split())
    memo.add((h,w))
    h_count[h] += 1
    w_count[w] += 1

h_memo = []
temp = 0
h_max = max(h_count)
for idx, i in enumerate(h_count):
    if i == h_max:
        h_memo.append(idx)

w_memo = []
temp = 0
w_max = max(w_count)
for idx, i in enumerate(w_count):
    if i == w_max:
        w_memo.append(idx)

for i in h_memo:
    for j in w_memo:
        if (i,j) not in memo:
            print(h_max + w_max)
            quit()
print(h_max + w_max - 1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

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

cnth = [0]*h
cntw = [0]*w
target = set()
for i in range(m):
    x,y = map(int,input().split())
    x -= 1
    y -= 1
    cnth[x] += 1
    cntｗ[y] += 1
    target.add(x*10**20 + y)

maxh = max(cnth)
maxw = max(cntw)
ans = maxh + maxw

H, W = set(),set()
for i,c in enumerate(cnth):
    if c == maxh:
        H.add(i)
for i,c in enumerate(cntw):
    if c == maxw:
        W.add(i)
if len(H)*len(W) > m:
    print(ans)
else:
    for h in H:
        for w in W:
            if h*10**20 + w not in target:
                print(ans)
                exit()
    print(ans-1)

Submission status: Accepted

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

hws_set = set(hws)
h_count = [0] * (H+1)
w_count = [0] * (W+1)
for h, w in hws:
    h_count[h] += 1
    w_count[w] += 1

max_h_count = max(h_count)
max_h_count_index = [i for i, c in enumerate(h_count) if c == max_h_count]
max_w_count = max(w_count)
max_w_count_index = [i for i, c in enumerate(w_count) if c == max_w_count]

if len(max_h_count_index) * len(max_w_count_index) > M:
    ans = max_h_count + max_w_count
else:
    ans = max_h_count + max_w_count - 1
    for i in max_h_count_index:
        for j in max_w_count_index:
            if (i, j) not in hws_set:
                ans += 1
                break
        else:
            continue
        break

print(ans)

Submission status: Accepted

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"

def main():
    h,w,m = map(int,ipt().split())
    hs = [0]*h
    ws = [0]*w
    base = 3*10**5
    st = set()
    for i in range(m):
        hi,wi = map(int,ipt().split())
        hs[hi-1] += 1
        ws[wi-1] += 1
        st.add((hi-1,wi-1))

    hma = max(hs)
    mah = []
    for i,hi in enumerate(hs):
        if hi == hma:
            mah.append(i)
    wma = max(ws)
    maw = []
    for i,wi in enumerate(ws):
        if wi == wma:
            maw.append(i)

    for i in mah:
        for j in maw:
            if not (i,j) in st:
                print(hma+wma)
                exit()

    print(hma+wma-1)

    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

"""

縦横の最大の組を抽出
組の数の積がMより大きかったら和を出せばいい
それ以外は全探索

"""

from sys import stdin
import sys
H,W,M = map(int,stdin.readline().split())

Hdic = {}
Wdic = {}
HW = {}

for i in range(M):

    h,w = map(int,stdin.readline().split())
    HW[(h,w)] = i

    if h not in Hdic:
        Hdic[h] = []
    Hdic[h].append(w)

    if w not in Wdic:
        Wdic[w] = []
    Wdic[w].append(h)

hmax = 0
hmlis = []

for i in Hdic:
    if len(Hdic[i]) > hmax:
        hmax = len(Hdic[i])
        hmlis = []

    if len(Hdic[i]) == hmax:
        hmlis.append(i)

wmax = 0
wmlis = []

for i in Wdic:
    if len(Wdic[i]) > wmax:
        wmax = len(Wdic[i])
        wmlis = []

    if len(Wdic[i]) == wmax:
        wmlis.append(i)

if len(hmlis) * len(wmlis) > M:
    print (hmax + wmax)
else:

    for h in hmlis:
        for w in wmlis:
            if (h,w) not in HW:
                print (hmax + wmax)
                sys.exit()

    print (hmax + wmax - 1)

Submission status: Accepted

Solution code:
import sys
from collections import Counter

stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    h, w, m = nm()
    H = []
    W = []
    for i in range(m):
        hh, ww = nm()
        H.append(hh)
        W.append(ww)
    h_m = Counter(H).most_common()[0]
    w_m = Counter(W).most_common()[0]
    ans_1 = h_m[1]
    ans_2 = w_m[1]
    WW = []
    HH = []

    for i in range(m):
        if H[i] == h_m[0]:
            continue
        WW.append(W[i])

    for i in range(m):
        if W[i] == w_m[0]:
            continue
        HH.append(H[i])
    if WW:
        ans_1 += Counter(WW).most_common()[0][1]
    if HH:
        ans_2 += Counter(HH).most_common()[0][1]

    print(max(ans_1, ans_2))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h,w,m = map(int,input().split())
br = [[i, 0] for i in range(h)]
bc = [[i, 0] for i in range(w)]
bsr = [set() for i in range(h)]
bsc = [set() for i in range(w)]
for _ in range(m):
    i, j = map(int,input().split())
    br[i-1][1] += 1
    bc[j-1][1] += 1
    bsr[i-1].add(j-1)
    bsc[j-1].add(i-1)
br.sort(key=lambda x: x[1], reverse=True)
bc.sort(key=lambda x: x[1], reverse=True)
rmax = br[0][1]
cmax = bc[0][1]
for i,bi in br:
    if bi < rmax:
        break
    for j, bj in bc:
        if bj < cmax:
            break
        if not j in bsr[i]:
            print(rmax + cmax)
            exit()

print(rmax + cmax - 1)

Submission status: Accepted

Solution code:
h, w, m = map(int, input().split())
a = [0] * h
b = [0] * w
g = [[] for _ in range(h)]
for _ in range(m):
    y, x = map(int, input().split())
    a[y - 1] += 1
    b[x - 1] += 1
    g[y - 1].append(x - 1)
ma = max(a)
mb = max(b)
c = b.count(mb)
for i in range(h):
    if a[i] == ma:
        res = 0
        for p in g[i]:
            if b[p] == mb:
                res += 1
        if res < c:
            print(ma + mb)
            exit(0)
print(ma + mb - 1)

Submission status: Accepted

Solution code:
import sys
h,w,n=map(int,input().split())
obj=set()
hor=[0]*(h+1)
ver=[0]*(w+1)
for i in range(n):
  x,y=map(int,input().split())
  obj.add((x-1)+(y-1)*h)
  hor[x]+=1
  ver[y]+=1
maxh=max(hor)
maxv=max(ver)
maxhct=0
maxvct=0
hs=[]
vs=[]
for i in range(1,h+1):
  if hor[i]==maxh:
    maxhct+=1
    hs.append(i)
for i in range(1,w+1):
  if ver[i]==maxv:
    maxvct+=1
    vs.append(i)
if maxhct*maxvct>n:
  print(maxh+maxv)
  sys.exit()
for i in hs:
  for j in vs:
    if not (((i-1)+(j-1)*h) in obj):
      print(maxh+maxv)
      sys.exit()
print(maxh+maxv-1)

Submission status: Accepted

Solution code:
h, w, m = map(int, input().split())
lo = 0x80000
t = [tuple(map(int, input().split())) for _ in range(m)]
seg = [0] * (lo * 2)
def modify(k, v):
    i = k + lo
    seg[i] += v
    i >>= 1
    while i:
        seg[i] = max(seg[i << 1], seg[(i << 1) | 1])
        i >>= 1
wow = [[] for _ in range(h + 3)]
for x, y in t:
    wow[x].append(y)
    modify(y, 1)
ans = 0
for x in range(1, h + 1):
    cc = 0
    for y in wow[x]:
        cc += 1
        modify(y, -1)
    ans = max(ans, cc + seg[1])
    for y in wow[x]:
        modify(y, 1)
print(ans)

Submission status: Accepted

Solution code:
h, w, m = map(int, input().split())
H = [0 for i in range(h + 1)]
W = [0 for i in range(w + 1)]
b = set()
for i in range(m):
    hi, wi = map(int, input().split())
    H[hi] += 1
    W[wi] += 1
    b.add((hi, wi))
h_list = []
w_list = []
temp = max(H)
for i in range(len(H)):
    if H[i] == temp:
        h_list.append(i)
temp2 = max(W)
for i in range(len(W)):
    if W[i] == temp2:
        w_list.append(i)
flag = False
for i in h_list:
    for j in w_list:
        if (i, j) not in b:
            flag = True
            break
    if flag == True:
        break
if flag == True:
    print(temp + temp2)
else:
    print(temp + temp2 - 1)

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9


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

    H, W, M = map(int, input().split())
    cnt_h = [0] * (H+1)
    cnt_w = [0] * (W+1)
    B = set()
    for _ in range(M):
        h, w = map(int, input().split())
        cnt_h[h] += 1
        cnt_w[w] += 1
        B.add(h * (W+1) + w)

    hmax = max(cnt_h)
    wmax = max(cnt_w)
    h_list = []
    w_list = []
    for h in range(1, H+1):
        if cnt_h[h] == hmax:
            h_list.append(h)
    for w in range(1, W+1):
        if cnt_w[w] == wmax:
            w_list.append(w)
    if len(h_list) * len(w_list) > M:
        print(hmax + wmax)
    else:
        flg = 1
        for h in h_list:
            for w in w_list:
                if h * (W+1) + w not in B:
                    flg = 0
                    break
        print(hmax + wmax - flg)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


h,w,m = list(map(int, input().split()))
hw = []
hs = [0]*h
ws = [0]*w
for i in range(m):
    hh,ww = map(int, input().split())
    hh -= 1
    ww -= 1
    hw.append((hh,ww))
    hs[hh] += 1
    ws[ww] += 1
# from heapq import heappop as hpp, heappush as hp
hs = [(v,i) for i,v in enumerate(hs)]
ws = [(v,i) for i,v in enumerate(ws)]
hs.sort(reverse=True)
ws.sort(reverse=True)
lh = set()
lw = set()
vh = hs[0][0]
vw = ws[0][0]
for i in range(h):
    if hs[i][0]!=vh:
        break
    else:
        lh.add(hs[i][1])
for i in range(w):
    if ws[i][0]!=vw:
        break
    else:
        lw.add(ws[i][1])
ans = vh + vw
val = len(lh)*len(lw)
for ih, iw in hw:
    if ih in lh and iw in lw:
        val -= 1
if val==0:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()

class SegmentTree(object):
    def __init__(self, A, dot, unit):
        n = 1 << (len(A) - 1).bit_length()
        tree = [unit] * (2 * n)
        for i, v in enumerate(A):
            tree[i + n] = v
        for i in range(n - 1, 0, -1):
            tree[i] = dot(tree[i << 1], tree[i << 1 | 1])
        self._n = n
        self._tree = tree
        self._dot = dot
        self._unit = unit

    def __getitem__(self, i):
        return self._tree[i + self._n]

    def update(self, i, v):
        i += self._n
        self._tree[i] = v
        while i != 1:
            i >>= 1
            self._tree[i] = self._dot(self._tree[i << 1], self._tree[i << 1 | 1])

    def add(self, i, v):
        self.update(i, self[i] + v)

    def sum(self, l, r):
        l += self._n
        r += self._n
        l_val = r_val = self._unit
        while l < r:
            if l & 1:
                l_val = self._dot(l_val, self._tree[l])
                l += 1
            if r & 1:
                r -= 1
                r_val = self._dot(self._tree[r], r_val)
            l >>= 1
            r >>= 1
        return self._dot(l_val, r_val)

def resolve():
    h, w, m = map(int, input().split())
    A = [[] for _ in range(h)]
    tree = SegmentTree([0] * w, max, 0)
    for _ in range(m):
        i, j = map(int, input().split())
        i -= 1; j -= 1
        A[i].append(j)
        tree.add(j, 1)

    ans = 0
    for i in range(h):
        for j in A[i]:
            tree.add(j, -1)
        ans = max(ans, len(A[i]) + tree.sum(0, w))
        for j in A[i]:
            tree.add(j, 1)

    print(ans)
resolve()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readlines = sys.stdin.buffer.readlines
input = sys.stdin.buffer.readline
H, W, M = map(int, input().split())

HH = [0]*H
WW = [0]*W
d = set()
for line in readlines():
    h, w = map(int, line.split())
    h -= 1
    w -= 1
    d.add((h, w))
    HH[h] += 1
    WW[w] += 1

m = -1
argm = []
for i, c in enumerate(HH):
    if c > m:
        m = c
        argm = [i]
    elif c == m:
        argm.append(i)

mH = m
aH = argm

m = -1
argm = []
for i, c in enumerate(WW):
    if c > m:
        m = c
        argm = [i]
    elif c == m:
        argm.append(i)

mW = m
aW = argm

ans = mH + mW
for h in aH:
    for w in aW:
        if (h, w) not in d:
            break
    else:
        continue
    break
else:
    ans -= 1

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right
from itertools import accumulate

sys.setrecursionlimit(10**6)
INF = 10**12
m = 10**9 + 7

def main():
    H, W, M = map(int, input().split())
    h = [0] * H
    w = [0] * W
    hw = set()
    for i in range(M):
        tmph, tmpw = map(lambda x: int(x)-1, input().split())
        h[tmph] += 1
        w[tmpw] += 1
        hw.add((tmph,tmpw))
    # 最大値より1だけ小さくなる物が候補
    HMAX = max(h)
    h0 = []
    for i in range(H):
        if h[i] == HMAX:
            h0.append(i)

    WMAX = max(w)
    w0 = []
    for i in range(W):
        if w[i] == WMAX:
            w0.append(i)

    ans = 0
    for i in h0:
        for j in w0:
            if (i,j) not in hw:
                print(HMAX+WMAX)
                exit()
    print(HMAX+WMAX-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
def input():return sys.stdin.readline()[:-1]
def N(): return int(input())
def NM():return map(int,input().split())
def L():return list(NM())

H,W,m=NM()
import collections
hl=collections.defaultdict(int)
wl=collections.defaultdict(int)
hwl=set()
for i in range(m):
    h,w=NM()
    hl[h]+=1
    wl[w]+=1
    hwl.add((h,w))
mh=0
mw=0
mhl=[]
mwl=[]
for k,v in hl.items():
    if mh<v:
        mh=v
        mhl=[k]
    elif mh==v:
        mhl.append(k)
for k,v in wl.items():
    if mw<v:
        mw=v
        mwl=[k]
    elif mw==v:
        mwl.append(k)
if len(mhl)*len(mwl)>m:
    print(min(m,mh+mw))
else:
    for i in mhl:
        for j in mwl:
            if not (i,j) in hwl:
                print(min(m,mh+mw))
                quit()
    print(mh+mw-1)

Submission status: Accepted

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

H, W, M = map(int, input().split())
st = set()
row = [0] * H
col = [0] * W
for _ in range(M):
    h, w = map(lambda x: int(x) - 1, input().split())
    st.add((h, w))
    row[h] += 1
    col[w] += 1
maxrow = []
maxcol = []
mr = max(row)
for i, r in enumerate(row):
    if r == mr:
        maxrow.append(i)
mc = max(col)
for j, c in enumerate(col):
    if c == mc:
        maxcol.append(j)
if len(maxrow) * len(maxcol) > M:
    print(mr + mc)
else:
    ok = False
    for r in maxrow:
        for c in maxcol:
            if (r, c) not in st:
                print(mr + mc)
                ok = True
                break
        if ok:
            break
    if not ok:
        print(mr + mc - 1)

Submission status: Accepted

Solution code:
import sys
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy

def solve():
    h, w, m = getList()
    gg = defaultdict(list)
    hh = defaultdict(list)
    ald = set()
    for i in range(m):
        a, b = getList()
        gg[a].append(b)
        hh[b].append(a)
        ald.add(a * 10 ** 6 + b)
    ma = -1
    ai = []
    for i in range(h+1):
        if ma < len(gg[i]):
            ma = len(gg[i])
            ai = [i]
        elif ma == len(gg[i]):
            ai.append(i)
    mb = -1
    bi = []
    for i in range(w+1):
        if mb < len(hh[i]):
            mb = len(hh[i])
            bi = [i]
        elif mb == len(hh[i]):
            bi.append(i)
    # print(gg, hh)
    # print(ma, ai, mb, bi)
    ans = ma + mb
    for aa in ai:
        for bb in bi:
            if (aa * 10 ** 6 + bb) not in ald:
                print(ans)
                return

    print(ans-1)
    return

def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()