Problem:
 Score : 700 points    Problem Statement Takahashi is hosting an sports meet.
There are N people who will participate. These people are conveniently numbered 1 through N .
Also, there are M options of sports for this event. These sports are numbered 1 through M .
Among these options, Takahashi will select one or more sports (possibly all) to be played in the event.  Takahashi knows that Person i 's j -th favorite sport is Sport A_{ij} .
Each person will only participate in his/her most favorite sport among the ones that are actually played in the event, and will not participate in the other sports.  Takahashi is worried that one of the sports will attract too many people.
Therefore, he would like to carefully select sports to be played so that the number of the participants in the sport with the largest number of participants is minimized.
Find the minimum possible number of the participants in the sport with the largest number of participants.      Constraints  1 \leq N \leq 300  1 \leq M \leq 300  A_{i1} , A_{i2} , ... , A_{iM} is a permutation of the integers from 1 to M .         Input Input is given from Standard Input in the following format:  N  M  A_{11}  A_{12}  ...  A_{1M}  A_{21}  A_{22}  ...  A_{2M}  :  A_{N1}  A_{N2}  ...  A_{NM}       Output Print the minimum possible number of the participants in the sport with the largest number of participants.        Sample Input 1 4 5
5 1 3 4 2
2 5 3 1 4
2 3 1 4 5
2 5 4 3 1      Sample Output 1 2  Assume that Sports 1 , 3 and 4 are selected to be played. In this case, Person 1 will participate in Sport 1 , Person 2 in Sport 3 , Person 3 in Sport 3 and Person 4 in Sport 4 .
Here, the sport with the largest number of participants is Sport 3 , with two participants.
There is no way to reduce the number of participants in the sport with the largest number of participants to 1 . Therefore, the answer is 2 .       Sample Input 2 3 3
2 1 3
2 1 3
2 1 3      Sample Output 2 3  Since all the people have the same taste in sports, there will be a sport with three participants, no matter what sports are selected.
Therefore, the answer is 3 .

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, M = MAP()
A = list2d(N, M, 0)
for i in range(N):
    for j, a in enumerate(LIST()):
        
        A[i][a-1] = j

k = 0
valid = [1] * M
ans = INF
while k < M:
    cnt = [0] * M
    for i in range(N):
        mn = INF
        idx = -1
        for j in range(M):
            if valid[j] and A[i][j] < mn:
                mn = A[i][j]
                idx = j
        
        cnt[idx] += 1
    mx = max(cnt)
    ans = min(ans, mx)
    for i in range(M):
        
        if cnt[i] == mx:
            valid[i] = 0
            k += 1
print(ans)

Solution (Python):

N,M = map(int,input().split())

A = []

for i in range(N):

    a = list(map(int,input().split()))
    A.append(a)

use = [True] * M

maxind = None
ans = float("inf")

for i in range(M):

    maxind = 0
    x = [0] * M
    
    for j in range(N):
        for k in range(M):
            if use[ A[j][k] - 1 ]:
                x[ A[j][k] - 1 ] += 1
                break

    for j in range(M):
        if x[maxind] < x[j]:
            maxind = j

    ans = min( ans , x[maxind] )
    use[maxind] = False

print (ans)

Solution (Python):
n, m = map(int, input().split())
A = [list(map(int, input().split()))[::-1] for _ in range(n)]
ans = n
for _ in range(m):
  C = [0]*m
  for i in A:
    C[i[-1]-1] += 1
  t = max(C)
  ans = min(ans, t)
  l = C.index(t)+1
  for i in A:
    i.remove(l)
print(ans)

Solution (Python):
n,m = map(int, input().split())


a = []
for i in range(n):
    b = list(map(int, input().split()))
    for j in range(len(b)):
        b[j]-=1
    a.append(b)


held_sports = [1 for i in range(m)]


join_sports = [0 for i in range(n)]

ans = n
for k in range(m):
    
    total_join_sports = [0 for i in range(m)]
    for i in range(n):
        
        x = join_sports[i]
        total_join_sports[a[i][x]]+=1

    
    sports = [0,0]
    for i in range(m):
        if total_join_sports[i]>sports[1]:
            sports = [i,total_join_sports[i]]

    
    ans = min(ans, sports[1])

    
    held_sports[sports[0]]=0

    
    for i in range(n):
        
        x = join_sports[i]
        if a[i][x]==sports[0]:
            
            for j in range(x+1,m):
                if held_sports[a[i][j]]==1:
                    join_sports[i]=j
                    break
print(ans)

Solution (Python):
N,M = map(int,input().split())
A = [[0 for _ in range(M+1)]]
for _ in range(N):
    a = list(map(int,input().split()))
    a.insert(0,0)
    A.append(a)
C = {j:[] for j in range(1,M+1)}
hist = [0 for _ in range(N+1)]
sports = [j for j in range(1,M+1)]
cmin = N
while len(sports)>1:
    for i in range(1,N+1):
        if hist[i]==0:
            for j in range(1,M+1):
                if A[i][j] in sports:
                    C[A[i][j]].append(i)
                    hist[i]=1
                    break
    cmax = 0
    smax = 0
    for a in sports:
        if len(C[a])>cmax:
            cmax = len(C[a])
            smax = a
    cmin = min(cmin,cmax)
    for i in C[smax]:
        hist[i]=0
    del C[smax]
    sports.remove(smax)
print(cmin)

Solution (Python):
import sys
import numpy as np

stdin = sys.stdin
 
ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split()))
rs = lambda: stdin.readline().rstrip()  

N, M = rl()
A = np.array([rl() for _ in range(N)])
answer = 300
for _ in range(M):
    counter = np.bincount(A[:, 0])
    i = np.argmax(counter)
    x = counter[i]
    if x < answer:
        answer = x
    A = A[A != i].reshape(N, -1)

print(answer)

Solution (Python):
import sys
from collections import Counter

stdin = sys.stdin
 
ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split()))
rs = lambda: stdin.readline().rstrip()  

N, M = rl()
A = [rl() for _ in range(N)]
answer = 300
while A[0]:
    s = set()
    l = []
    
    for i in range(N):
        x = A[i][0]
        s.add(x)
        l.append(x)
    
    c = Counter(l)
    y = c.most_common(1)[0]
    answer = min(answer, y[1])
    for i in range(N):
        A[i].remove(y[0])

print(answer)

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    n,m=map(int,input().split())
    A=[list(map(lambda x:int(x)-1,input().split())) for _ in range(n)]
    ans=INF

    for _ in range(m):
        C=[0]*m 
        for i in range(n):
            for j in range(m):
                if(A[i][j] is not None):
                    C[A[i][j]]+=1
                    break
        M=max(C)
        ans=min(ans,M)
        ind=C.index(M)
        for i in range(n):
            for j in range(m):
                if(A[i][j]==ind):
                    A[i][j]=None

    print(ans)
resolve()

Solution (Python):
from collections import Counter as C
N, M = map(int, input().split())
A = [[int(a)-1 for a in input().split()] for _ in range(N)]
X = [1] * M
mi = 1 << 100
for i in range(M):
    c = C([min([(j, A[i][j]) for j in range(M) if X[A[i][j]]])[1] for i in range(N)])
    a = max([(c[a], a) for a in c])[1]
    mi = min(mi, c[a])
    X[a] -= 1
print(mi)

Solution (Python):
import sys
input = sys.stdin.buffer.readline

n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
cnt = [0] * (m + 1)
cur = [[0, 0] for _ in range(n)]
done = set()
for i in range(n):
	cnt[a[i][0]] += 1
	cur[i][1] = a[i][0]
ans = max(cnt)
for _ in range(m - 1):
	col = cnt.index(max(cnt))
	done.add(col)
	for i in range(n):
		if cur[i][1] == col:
			j = cur[i][0]
			while a[i][j] in done:
				j += 1
			t = a[i][j]
			cur[i] = [j, t]
			cnt[t] += 1
	cnt[col] = 0
	ans = min(ans, max(cnt))
print(ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline

n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
cnt = [0] * (m + 1)
cur = [0] * n
cur_idx = [0] * n
done = [0] * (m + 1)
for i in range(n):
	cnt[a[i][0]] += 1
	cur[i] = a[i][0]
ans = max(cnt)
for _ in range(m - 1):
	col = cnt.index(max(cnt))
	done[col] = 1
	for i in range(n):
		if cur[i] == col:
			j = cur_idx[i]
			while done[a[i][j]]:
				j += 1
			t = a[i][j]
			cur[i] = t
			cur_idx[i] = j
			cnt[t] += 1
	cnt[col] = 0
	ans = min(ans, max(cnt))
print(ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline

n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
cnt = [0] * (m + 1)
cur = [0] * n
done = [0] * (m + 1)
for i in range(n):
	cnt[a[i][0]] += 1
	cur[i] = a[i][0]
ans = max(cnt)
for _ in range(m - 1):
	col = cnt.index(max(cnt))
	done[col] = 1
	for i in range(n):
		if cur[i] == col:
			j = 0
			while done[a[i][j]]:
				j += 1
			t = a[i][j]
			cur[i] = t
			cnt[t] += 1
	cnt[col] = 0
	ans = min(ans, max(cnt))
print(ans)

Solution (Python):



def solve():
    from operator import itemgetter

    n, m = map(int, input().split())
    a = tuple([int(x) - 1 for x in reversed(input().split())] for _ in range(n))
    excluded = [False] * m

    ret = n
    for _ in range(m):
        cnt = [0] * m
        for p in a:
            while excluded[p[-1]]:
                p.pop()
            cnt[p[-1]] += 1
        j, c = max(enumerate(cnt), key=itemgetter(1))
        ret = min(ret, c)
        excluded[j] = True
    return ret


print(solve())

Solution (Python):



from collections import deque
from operator import itemgetter


def solve(n, m, prefers):
    def sub(prefers, canceled):
        ret = [0] * m
        for pref in prefers:
            while canceled[pref[0]]:
                pref.popleft()
            ret[pref[0]] += 1
        return max(enumerate(ret), key=itemgetter(1))

    canceled = [False] * m
    ret = n
    for _ in range(m):
        s, c = sub(prefers, canceled)
        canceled[s] = True
        ret = min(ret, c)
    return ret


if __name__ == '__main__':
    n, m = map(int, input().split())
    prefers = [deque(int(x) - 1 for x in input().split()) for _ in range(n)]
    print(solve(n, m, prefers))

Solution (Python):
def solve(mid):
    set_ = set([])
    memo = {}
    ind = [0] * n
    while True:
        memo = {}
        for i, j in enumerate(ind):
            if a[i][j] not in memo:
                memo[a[i][j]] = [i]
            else:
                memo[a[i][j]].append(i)
        for i in memo:
            if len(memo[i]) > mid:
                tmp = i
                set_.add(i)
                break
        else:
            return True
          
        for i in memo[tmp]:
            index = ind[i]
            while True:
                if index >= m:
                    return False
                if a[i][index] in set_:
                    index += 1
                else:
                    ind[i] = index
                    break


n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]

ok = n
ng = 0
while abs(ok - ng) > 1:
    mid = (ok + ng) // 2
    if solve(mid):
        ok = mid
    else:
        ng = mid
print(ok)

Solution (Python):
def main():
    from collections import Counter as ct
    n,m=map(int,input().split())
    a=[list(map(int,input().split())) for _ in [0]*n]
    ret=n
    for _ in range(m):
        ans=[]
        for i in range(n):
            ans.append(a[i][0])
        j,k=ct(ans).most_common()[0]
        ret=min(k,ret)
        for i in range(n):
            a[i].remove(j)
    print(ret)
main()

Solution (Python):
N, M = map(int,input().split())
A = list(list(map(int,input().split()))+[0] for i in range(N))
p = [0]*N
s = [0]*(M+1)
ans = N
for _ in range(M):
    count = [0] * (M+1)
    for i in range(N):
        count[A[i][p[i]]] += 1
    hoge = max(count)
    ans = min(ans,hoge)
    s[count.index(hoge)] = 1
    for i in range(N):
        while s[A[i][p[i]]]:
            p[i] += 1
print(ans)

Solution (Python):
from collections import Counter

N, M = map(int, input().split())
A = [[int(i) for i in input().split()] for _ in range(N)]

for i in range(N) :
    A[i] = A[i][::-1]

def solve() :
    ret = float('inf')
    select = [True] * (M + 1)

    while True :
        c = Counter([A[i][-1] for i in range(N)])
        for k, v in c.items() :
            if v >= ret :
                select[k] = False
                
        ret = min(ret, max(c.values()))
        
        for i in range(N) :
            while not select[A[i][-1]] :
                A[i].pop()
                if len(A[i]) == 0 :
                    return ret
                    
print(solve())

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, M, A):
    ans = INF
    s = set(range(1, M+1))
    for _ in range(M):
        c = Counter()
        for a in A:
            for b in a:
                if b in s:
                    c[b] += 1
                    break
        k, v = c.most_common()[0]
        
        ans = min(ans, v)
        s.remove(k)
    return ans


def main():
    N, M = read_int_n()
    A = [read_int_n() for _ in range(N)]
    print(slv(N, M, A))


if __name__ == '__main__':
    main()

Solution (Python):
import collections
import fractions
N,M=map(int,input().split())
A=[list(map(int,input().split())) for i in range(N)]

lst=set()
value=0
for k in range(M):
    data=[0 for m in range(0,M+1)]
    for n in range(N):
        for m in range(M):
            if A[n][m] not in lst:
                data[A[n][m]]+=1
                break
    
    if value==0:value=max(data)
    else:value=min(max(data),value)
    lst.add(data.index(max(data)))
print(value)

Solution (Python):
import numpy as np

def main():
    A = np.loadtxt(open(0), np.int32, skiprows=1, ndmin=2)

    N = ans = len(A)

    while A.any():
        b = np.bincount(A[:, 0])
        A = np.reshape(A[A != b.argmax()], (N, -1))
        ans = min(ans, b.max())

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np

def main():
    A = np.loadtxt(open(0), np.int32, skiprows=1, ndmin=2)

    N = ans = len(A)

    while A.any():
        b = np.bincount(A[:, 0])
        A = np.reshape(A[A != np.argmax(b)], (N, -1))
        ans = min(ans, max(b))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np

def main():
    A = np.loadtxt(open(0), np.int64, skiprows=1, ndmin=2)

    N = ans = len(A)

    while A.any():
        b = np.bincount(A[:, 0])
        A = np.reshape(A[A != np.argmax(b)], (N, -1))
        ans = min(ans, max(b))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np

A = np.loadtxt(open(0), np.int64, skiprows=1, ndmin=2)

N = ans = len(A)

while A.any():
    b = np.bincount(A[:, 0])
    A = np.reshape(A[A != np.argmax(b)], (N, -1))
    ans = min(ans, max(b))

print(ans)

Solution (Python):
from numpy import loadtxt, int64, bincount, reshape, argmax

A = loadtxt(open(0), int64, skiprows=1, ndmin=2)

N = ans = len(A)

while A.any():
    b = bincount(A[:, 0])
    A = reshape(A[A != argmax(b)], (N, -1))
    ans = min(ans, max(b))

print(ans)

Solution (Python):
from numpy import loadtxt, int64, bincount, reshape, argmax

A = loadtxt(open(0), int64, skiprows=1, ndmin=2)

N = ans = len(A)

while A.any():
    b = bincount(A[:, 0])
    A = reshape(A[A != b.argmax()], (N, -1))
    ans = min(ans, b.max())

print(ans)

Solution (Python):
from collections import defaultdict

N, M = map(int, input().split())
INF = float('inf')

A = [tuple(map(int, input().split())) for _ in range(N)]

def search(sports):
    if not sports:
        return INF

    cnt = [0] * (M + 1)
    for a in A:
        for p in a:
            if p in sports:
                cnt[p] += 1
                break

    ret = max(cnt)
    maxSport = cnt.index(ret)
    sports.remove(maxSport)

    return min(ret, search(sports))

ans = search(set(list(range(1, M + 1))))
print(ans)

Solution (Python):
from collections import Counter

n, m = map(int, input().split())
xss = [[int(x) for x in input().split()] for _ in range(n)]

needles = [0 for _ in range(n)]

ans = n
canceled = set()
while len(canceled)+1 < m:
    cnt = Counter(xs[needle] for needle, xs in zip(needles, xss))
    most = cnt.most_common(1)[0]
    ans = min(ans, most[1])
    canceled.add(most[0])
    for i, xs in enumerate(xss):
        while xs[needles[i]] in canceled:
            needles[i] += 1

print(ans)

Solution (Python):
n,m = map(int,input().split())
a = [list(map(int,input().split())) for _ in range(n)]
idx = [0]*(n+1)
taboo = set()
ans = n
for _ in range(m-1):
  part = [0]*(m+1)
  for i in range(n):
    while a[i][idx[i]] in taboo:
      idx[i] += 1
    part[a[i][idx[i]]] += 1
  cm = 0
  for j in range(1,m+1):
    if cm < part[j]:
      t = j
      cm = part[j]
  ans = min(ans,cm)
  taboo.add(t)
print(ans)

Solution (Python):
from collections import Counter

N, M = map(int, input().split())
A_list = []
for _ in range(N):
    a = list(map(int, input().split()))
    A_list.append(a)

ans = N
for _ in range(M-1):
    most_like_list = []
    for i in range(N):
        most_like_list.append(A_list[i][0])
    most_like, ans_new = Counter(most_like_list).most_common()[0]
    ans = min(ans, ans_new)
    for i in range(N):
        A_list[i].remove(most_like)

print(ans)

Solution (Python):
from subprocess import*
call(('python3','-c',"""
from numpy import*
a=loadtxt(open(0),'i',skiprows=1,ndmin=2)
n=x=len(a)
while a.any():
  t=bincount(a[:,0])
  x,a=min(x,max(t)),reshape(a[a!=argmax(t)],(n,-1))
print(x)
"""))

Solution (Python):
from numpy import*
a=loadtxt(open(0),'i',skiprows=1,ndmin=2)
n=x=len(a)
while a.any():
  t=bincount(a[:,0])
  x,a=min(x,max(t)),reshape(a[a!=argmax(t)],(n,-1))
print(x)

Solution (Python):
import sys
input = sys.stdin.readline

N, M = map(int, input().split())
state = [list(map(int, input().split())) for _ in range(N)]

l = 0
r = N+1

while r - l > 1:
    m = (l+r)//2
    ok = True
    canuse = [True]*(M+1)
    pri = [0]*N
    while ok:
        sport = [0]*(M+1)
        for i in range(N):
            while not canuse[state[i][pri[i]]]:
                pri[i] += 1
                if pri[i] > M-1:
                    ok = False
                    break
            if not ok:
                break
            sport[state[i][pri[i]]] += 1
        update = False
        for j in range(1, M+1):
            if sport[j] > m:
                update = True
                canuse[j] = False
        if not update:
            break
    
    if ok:
        r = m
    else:
        l = m
                
    
print(r)

Solution (Python):
from collections import Counter
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


N, M = map(int, input().split())
mat = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N)]

ans = N
Q = [set([v for v in range(M)])]
while Q:
    C = Counter()
    sports_cand = Q.pop(0)
    for n in range(N):
        for m in range(M):
            if mat[n][m] in sports_cand:
                C[mat[n][m]] += 1
                break
    tmp = 0
    rem_key = set()
    for key, val in C.most_common():
        if val >= tmp:
            tmp = val
            ans = min(ans, val)
            rem_key.add(key)
        else:
            break
    if len(sports_cand) > 2:
        Q.append(sports_cand-rem_key)
print(ans)

Solution (Python):
from collections import Counter
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


N, M = map(int, input().split())
mat = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N)]

ans = N
sports_cand = set([v for v in range(M)])
for _ in range(M-1):
    C = Counter()
    for n in range(N):
        for m in range(M):
            if mat[n][m] in sports_cand:
                C[mat[n][m]] += 1
                break
    tmp = 0
    key, val = C.most_common(1)[0]
    ans = min(ans, val)
    sports_cand -= {key}
print(ans)

Solution (Python):
from collections import Counter
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


N, M = map(int, input().split())
mat = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N)]

ans = N
Q = [set([v for v in range(M)])]
while Q:
    C = Counter()
    sports_cand = Q.pop(0)
    for n in range(N):
        for m in range(M):
            if mat[n][m] in sports_cand:
                C[mat[n][m]] += 1
                break
    tmp = 0
    for key, val in C.most_common():
        if val > tmp:
            tmp = val
            ans = min(ans, val)
            if len(sports_cand) > 2:
                Q.append(sports_cand-{key})
        else:
            break
print(ans)

Solution (Python):
N,M = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(N)]


ans = N
NG = [0 for _ in range(M)]
while(sum(NG)<M):
  COUNT = [0 for _ in range(M)]
  for i in range(N):
    for j in range(M):
      if NG[A[i][j]-1] == 0:
        COUNT[A[i][j]-1] += 1
        break
  maxcount = 0
  maxi = 0
  for i in range(M):
    if maxcount < COUNT[i]:
      maxcount = COUNT[i]
      maxi = i
  
  ans = min(ans,maxcount)
  NG[maxi] = 1
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(pow(10, 6))
from collections import defaultdict


def main():
    n, m = map(int, input().split())
    a = []
    for _ in range(n):
        a.append(list(map(int, input().split())))
    
    if m==1:
        print(n)
        return
    
    sports = [1 for _ in range(m)]
    ans = 10**18
    for _ in range(m-1):
        sdic = defaultdict(lambda: 0)
        for _al in a:
            for _a in _al:
                if sports[_a-1] == 1:
                    sdic[_a] += 1
                    break
        tmp = list(sorted(sdic.items(), key=lambda x: x[1]))[-1]
        ans = min(ans, tmp[1])
        sports[tmp[0]-1] = 0
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N,M=map(int,input().split())
A=[list(map(int,input().split())) for i in range(N)]
g=[1]*M
G=M
I=[0]*N
R=N
def count(x):
    c=[0]*M
    r,ri=0,0
    for e in x:
        c[e]+=1
        if c[e]>r:
            r=c[e]
            ri=e
    return r,ri
while G>0:
    for l,a in enumerate(A):
        while g[a[I[l]]-1]==0:
            I[l]+=1
    r,ri=count([a[I[l]]-1 for l,a in enumerate(A)])
    R=min(R,r)
    g[ri]=0
    G-=1
print(R)

Solution (Python):
import collections
N, M = [int(_) for _ in input().split()]
A = [[int(_) for _ in input().split()][::-1] for _ in range(N)]
ng = set()
ans = float('inf')
for m in range(M):
    cnt = collections.defaultdict(int)
    for n in range(N):
        while True:
            if A[n][-1] in ng:
                A[n].pop()
            else:
                cnt[A[n][-1]] += 1
                break
    y = max(cnt, key=lambda x: cnt[x])
    ans = min(ans, cnt[y])
    ng.add(y)
print(ans)

Solution (Python):
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))



from collections import Counter

N,M = II()
A = []
for _ in range(N):
    A.append(III())

used = [False]*(M+1)
place = [0]*N
elements = [0]*N
for i in range(N):
    elements[i] = A[i][0]

ans = float('inf')
for i in range(M):
    c = Counter(elements)
    val = c.most_common(1)[0][0]
    num = c.most_common(1)[0][1]
    if num<ans:
        ans = num
    used[val] = True
    index_list = []
    for j,e in enumerate(elements):
        if e==val:
            index_list.append(j)
    for index in index_list:
        for p in range(place[index],M):
            if used[A[index][p]]:
                continue
            else:
                elements[index] = A[index][p]
                place[index] = p+1
                break

print(ans)

Solution (Python):
from collections import deque, defaultdict

n,m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
def check(x):
    """
    最大値をx以下にできるか？
    """
    used = [0]*n
    if x >= n:
        return True
    
    b = [deque(a[i]) for i in range(n)]
    d = defaultdict(list)

    ng = set()
    while True:
        for i in range(n):
            if used[i]:
                continue
            while b[i] and b[i][0] in ng:
                b[i].popleft()
            if not b[i]:
                return False
            like = b[i].popleft()

            d[like].append(i)
            used[i] = 1
        
        flag = True
        for key, value in d.items():
            if len(value) > x:
                flag = False
                ng.add(key)
                for v in value:
                    used[v] = 0
                d[key] = []
        if flag:
            return True

left = 0
right = n
while right - left > 1:
    mid = (left+right)//2
    if check(mid):
        right = mid
    else:
        left = mid
print(right)

Solution (Python):
from collections import deque, defaultdict

n,m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]

def check(x):
    used = [0]*n
    if x >= n:
        return True
    
    b = [deque(a[i]) for i in range(n)]
    d = defaultdict(list)

    ng = set()
    while True:
        for i in range(n):
            if used[i]:
                continue
            while b[i] and b[i][0] in ng:
                b[i].popleft()
            if not b[i]:
                return False
            like = b[i].popleft()

            d[like].append(i)
            used[i] = 1
        
        flag = True
        for key, value in d.items():
            if len(value) > x:
                flag = False
                ng.add(key)
                for v in value:
                    used[v] = 0
                d[key] = []
        if flag:
            return True

left = 0
right = n+1
while right - left > 1:
    mid = (left+right)//2
    if check(mid):
        right = mid
    else:
        left = mid
print(right)

Solution (Python):
N, M = map(int, input().split())
A = [list(map(int, input().split())) for i in range(N)]


def calc(hold):
    participants = {i: 0 for i in range(1, M + 1)}
    for person in A:
        for sport in person:
            if sport not in hold:
                continue
            participants[sport] += 1
            break
    return participants


X = set(list(range(1, M + 1)))
ans = float('inf')
while X:
    ret_p = calc(X)
    max_participants = max(ret_p.values())
    ans = min(ans, max_participants)
    for key, value in ret_p.items():
        if value == max_participants:
            X.remove(key)
            break

print(ans)

Solution (Python):
from collections import Counter

N,M=map(int,input().split())

L=[]
for i in range(N):
    A=list(map(int,input().split()))
    L.append(A)
    
OUTD=dict()
S=[0 for i in range(N)]

ANS=1000
for i in range(M):
    B=[0 for _ in range(N)]
    for j in range(N):
        for k in range(S[j],M):
            if L[j][k] in OUTD:
                S[j]+=1
            else:
                B[j]=L[j][k]
                break
    X=Counter(B).most_common()[0]
    if X[1]<ANS:
        ANS=X[1]
    OUTD[X[0]]=1
    
print(ANS)

Solution (Python):



import sys
import math
import copy
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def f(flag):
    global ans
    cnt = [0]*m
    for i in range(n):
        for j in range(m):
            if flag[a[i][j]-1]:
                cnt[a[i][j]-1] += 1
                break
        else:
            return
    flag[cnt.index(max(cnt))] = False
    ans = min(ans,max(cnt))
    f(flag)
n,m = LI()
a = [LI() for _ in range(n)]
flag = [True]*m
ans = inf
f(flag)
print(ans)

Solution (Python):
from collections import defaultdict

N, M = map(int, input().split())

A = [list(map(int, input().split())) for _ in range(N)]

def search(sportList):
    if not sportList:
        return float('inf')

    cnt = defaultdict(int)

    for p in range(N):
        for a in A[p]:
            if a in sportList:
                cnt[a] += 1
                break

    maxSport = -1
    ret = -float('inf')
    for s, c in cnt.items():
        if ret < c:
            maxSport = s
            ret = c

    sportList.remove(maxSport)
    return min(cnt[maxSport], search(sportList))

sportList = set(range(1, M + 1))
ans = search(sportList)

print(ans)

Solution (Python):
N, M = map(int, input().split())
A = [[0 for _ in range(M)] for _ in range(N)]
for i in range(N):
  A[i] = [int(x) - 1 for x in input().split()]
S = [[0, i] for i in range(M)]
for a in A:
  S[a[0]][0] += 1
minmax = N
for _ in range(M - 1):
  _S = sorted(S, reverse=True)
  s = _S[0][1]
  minmax = min(S[s][0], minmax)
  S[s][0] = -1
  for a in A:
    if S[a[0]][0] > 0:
      continue
    while S[a[0]][0] < 0:
      a.pop(0)
    S[a[0]][0] += 1
print(minmax)

Solution (Python):
import os
import sys
from collections import Counter

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M = list(map(int, sys.stdin.readline().split()))
A = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]

A = np.array(A, dtype=int)
idx = np.zeros(N, dtype=int)
used = np.zeros(M + 1, dtype=bool)

ans = INF
for _ in range(M):
    k, cnt = Counter(A[np.arange(N), idx]).most_common(1)[0]
    ans = min(ans, cnt)
    used[k] = True
    for i in range(N):
        while idx[i] < M and used[A[i, idx[i]]]:
            idx[i] += 1
print(ans)