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):
N, M = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(N)]

R = {}
ans = N
cnt = [0] * N

for i in range(M):
  L = [0] * (M + 1)
  for j in range(N):
    while A[j][cnt[j]] in R:
      cnt[j] += 1
    L[A[j][cnt[j]]] += 1
  ma = 0
  man = L[0]
  for j in range(M + 1):
    if man < L[j]:
      ma = j
      man = L[j]
  ans = min(ans, man)
  R[ma] = 1

print(ans)

Solution (Python):
















n, m = list(map(int, input().split()))
preference = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] 

ans = n
held_sports = set(range(m))

while held_sports:
    
    parti = [0] * m
    for pref in preference:
        for s in pref:
            if s in held_sports:
                parti[s] += 1
                break
    
    temp = max(parti)
    ans = min(ans, temp)
    
    indices = [i for i,val in enumerate(parti) if val == temp]
    held_sports = held_sports - set(indices)

print(ans)

Solution (Python):
















n, m = list(map(int, input().split()))
preference = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] 

ans = n
held_sports = set(range(m))

while held_sports:
    
    parti = [0] * m
    for pref in preference:
        for s in pref:
            if s in held_sports:
                parti[s] += 1
                break
    
    temp = max(parti)
    ans = min(ans, temp)
    
    for idx, par in enumerate(parti):
        if par == temp:
            held_sports.remove(idx)

print(ans)

Solution (Python):
















n, m = list(map(int, input().split()))
preference = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] 

ans = n
held_sports = set(range(m))

while held_sports:
    
    parti = [0] * m
    for pref in preference:
        for s in range(m):
            if pref[s] in held_sports:
                parti[pref[s]] += 1
                break
    
    temp = max(parti)
    ans = min(ans, temp)
    
    for idx, par in enumerate(parti):
        if par == temp:
            held_sports.remove(idx)

print(ans)

Solution (Python):
















n, m = list(map(int, input().split()))
preference = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] 

ans = n
held_sports = set(range(m))

while held_sports:
    
    parti = [0] * m
    for person in range(n):
        for s in range(m):
            if preference[person][s] in held_sports:
                parti[preference[person][s]] += 1
                break
    
    temp = max(parti)
    ans = min(ans, temp)
    
    for idx, par in enumerate(parti):
        if par == temp:
            held_sports.remove(idx)

print(ans)

Solution (Python):
















n, m = list(map(int, input().split()))
preference = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] 

ans = n
held_sports = set(range(m))

while held_sports:
    
    parti = [0] * m
    for person in range(n):
        for s in range(m):
            if preference[person][s] in held_sports:
                parti[preference[person][s]] += 1
                break
    
    temp = max(parti)
    ans = min(ans, temp)
    
    for idx, par in enumerate(parti):
        if par == temp:
            held_sports.remove(idx)

print(ans)

Solution (Python):
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    A = [LI() for _ in range(N)]

    ctr = [0] * N

    sp = [0] * (M+1)
    for i in range(N):
        sp[A[i][ctr[i]]] += 1
    ans = max(sp)

    for _ in range(M-1):
        mi = sp.index(max(sp))
        sp[mi] = -1
        for i in range(N):
            if A[i][ctr[i]] == mi:
                while sp[A[i][ctr[i]]] < 0:
                    ctr[i] += 1
                sp[A[i][ctr[i]]] += 1
        ans = min(ans,max(sp))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    A = [LI() for _ in range(N)]

    ctr = [0] * N

    sp = [0] * (M+1)
    for i in range(N):
        sp[A[i][ctr[i]]] += 1
    ans = max(sp)

    for _ in range(M-1):
        m = 0
        mi = -1
        for i in range(1,M+1):
            if sp[i] > m:
                m = sp[i]
                mi = i
        sp[mi] = -1
        for i in range(N):
            if A[i][ctr[i]] == mi:
                while sp[A[i][ctr[i]]] < 0:
                    ctr[i] += 1
                sp[A[i][ctr[i]]] += 1
        ans = min(ans,max(sp))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict

def meguru_bisect(ng, ok):
    """
    初期値のng,okを受け取り, check=>Trueを満たす最大値(最小値)を返す
    条件を満たす最大値を求める場合、初期値は(ng:上限の外, ok:下限の外)   例) 10**9+1, -1
    条件を満たす最小値を求める場合、初期値は(ng:下限の外, ok:上限の外)   例) -1, 10**9+1
    上限の外や下限の外が返ってくる場合は条件を満たす値が範囲内になかったことを示すので、例外処理が必要
    """
    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if check(mid):
            ok = mid
        else:
            ng = mid
    return ok

def check(x):
    index = defaultdict(int)
    disused = set()
    while True:
        count = defaultdict(int)
        for i in range(n):
            while A[i][index[i]] in disused:
                index[i] += 1
                if index[i] >= m:
                    return False
            count[A[i][index[i]]] += 1
        max_count = max(count.values())
        if max_count <= x:
            return True
        else:
            disused.add([key for key, value in count.items() if value == max_count][0])

n, m = (int(x) for x in input().split())
A = [list(int(x) for x in input().split()) for _ in range(n)]
ans = meguru_bisect(0, n + 1)
print(ans)

Solution (Python):
from collections import Counter
n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
ans = float("inf")
for i in range(m):
    c = Counter([a[i][0] for i in range(n)])
    x, y = c.most_common()[0]
    ans = min(ans, y)
    for i in range(n):
        a[i].remove(x)
print(ans)

Solution (Python):
n,m = map(int,input().split())
a = [list(map(int,input().split())) for i in range(n)]
count = [0]*(m+1)
for i in a:
    count[i[0]] += 1
l = [0]*n
ans = max(count)
s = set()
for i in range(m-1):
    M = max(count)
    ind = count.index(M)
    s.add(ind)

    for j in range(n):
        if a[j][l[j]] == ind:

            count[ind] -= 1
            while a[j][l[j]] in s:
                l[j] += 1
            count[a[j][l[j]]] += 1
    ans = min(ans,max(count))

print(ans)

Solution (Python):
def main():
    n, m = map(int, input().split())
    a = [list(map(int, input().split())) for _ in range(n)]
    ans = n
    st = set(i for i in range(1, m+1))
    while len(st) > 1:
        dic = {v:0 for v in st}
        for i in range(n):
            for v in a[i]:
                if v in st:
                    dic[v] += 1
                    break
        tmp = max(dic.values())
        if ans > tmp:
            ans = tmp
        for key in dic.keys():
            if dic[key] == tmp:
                st.remove(key)
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n, m = map(int, input().split())
    a = [list(map(int, input().split())) for _ in range(n)]
    ans = n
    st = set(i for i in range(1, m+1))
    while len(st) > 1:
        dic = {v:0 for v in st}
        for i in range(n):
            for v in a[i]:
                if v in st:
                    dic[v] += 1
                    break
        tmp = max(dic.values())
        if ans > tmp:
            ans = tmp
        for key in dic.keys():
            if dic[key] == tmp:
                st.remove(key)
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("YES") if fl else print("NO")
import collections
import math
import itertools
import heapq as hq
def A_count():
    cnt = [0]*m
    for la in A:
        for a in la:
            if use[a]:
                cnt[a]+=1
                break
    heap = []
    for i in range(m):
        if use[i]:
            hq.heappush(heap,(-cnt[i],i))
    return heap

n,m = ma()
A = []
for i in range(n):
    A.append(list(map(lambda x:int(x)-1,input().split())))
ans = 10**9
use = [True]*m

for i in range(m):
    heap = A_count()
    mx,a = hq.heappop(heap)
    ans = min(ans,-mx)
    use[a]=False
print(ans)

Solution (Python):
def isok(k):
  b=[i[::-1] for i in a]
  d=[0]*(m+1)
  while all(b):
    flag=1
    c=[0]*(m+1)
    for i in range(n):
      c[b[i][-1]]+=1
    for i in range(n):
      if c[b[i][-1]]>k or d[b[i][-1]]:
        d[b[i][-1]]=1
        b[i].pop()
        flag=0
    if flag:break
  return all(b)
def bsearch(a):
  ok=n
  ng=-1
  while abs(ok-ng)>1:
    mid=(ok+ng)//2
    if isok(mid):ok=mid
    else:ng=mid
  return ok
n,m=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(n)]
print(bsearch(a))

Solution (Python):
N,M=map(int, input().split())
A=[]
for i in range(N):
  d=list(map(int, input().split()))
  A.append(d)
S=[1]*M
num=[0]*N
ans=N
for i in range(M):
  cnt=[0]*M
  for j in range(N):
    d=A[j][num[j]]
    while S[d-1]==0:
      num[j]+=1
      d=A[j][num[j]]
    cnt[d-1]+=1
  e=max(cnt)
  ans=min(e,ans)
  f=cnt.index(e)
  S[f]=0
print(ans)

Solution (Python):
def dfs(s):
    global ans
    if len(s)==M:
        return
    cnt=[0]*M
    for i in range(N):
        for j in range(M):
            if A[i][j] in s:
                continue
            cnt[A[i][j]]+=1
            break
    p=-1
    m=0
    for i in range(M):
        if cnt[i]>m:
            m=cnt[i]
            p=i
    ans=min(ans,m)
    s.add(p)
    dfs(s)
    return
N,M=map(int,input().split())
A=[list(map(lambda x:int(x)-1,input().split())) for i in range(N)]

ans=float('inf')
dfs(set())
print(ans)

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n, m = map(int, readline().split())
    a = []
    for i in range(n):
        a.append(list(map(int, readline().split())))

    ans = INF
    for _ in range(m):
        cnt = [0] * (m + 1)
        for i in range(n):
            cnt[a[i][0]] += 1
        max_cnt = max(cnt)
        ans = min(ans, max_cnt)
        max_num = cnt.index(max_cnt)
        for i in range(n):
            a[i].remove(max_num)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7
res = f_inf


def resolve():
    def dfs(remove):
        global res
        if len(remove) == m:
            return

        cnt = [0] * m
        ma = -f_inf
        target = None
        for i in range(n):
            for j in range(m):
                if A[i][j] not in remove:
                    cnt[A[i][j] - 1] += 1
                    if ma < cnt[A[i][j] - 1]:
                        ma = cnt[A[i][j] - 1]
                        target = A[i][j]
                    break

        remove.add(target)
        res = min(res, ma)
        dfs(remove)

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

    dfs(set())
    print(res)


if __name__ == '__main__':
    resolve()

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

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

A = [None] * N
for i in range(N):
  A[i] = list(map(int,readline().split()))[::-1]


from collections import defaultdict
counter = defaultdict(int)


removed = set()


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

target = max(counter, key = counter.get)

ans = max(counter.values()) 

while len(removed) < M - 1:
  
  for i in range(N):
    if len(A[i]) == 0:
      continue
    if A[i][-1] == target:
      A[i].pop()
      counter[target] -= 1
      while len(A[i]) > 0:
        if A[i][-1] in removed:
          A[i].pop()
        else:
          counter[A[i][-1]] += 1
          break
  removed.add(target)
  
  target = max(counter, key = counter.get)
  now = max(counter.values())
  if ans > now:
    ans = now
    
print(ans)

Solution (Python):
from collections import deque,Counter
n,m=map(int,input().split())
a=[deque(list(map(int,input().split()))) for _ in range(n)]
ans=n
no=set(())
while len(no)<m:
  for i in range(n):
    while a[i][0] in no:
      a[i].popleft()
  top=[a[i][0] for i in range(n)]
  ctop=Counter(top)
  mm=max(ctop.values())
  ans=min(ans,mm)
  for c in ctop:
    if ctop[c]==mm:
      no.add(c)
print(ans)

Solution (Python):
def main():
  import sys
  input=sys.stdin.buffer.readline
  N,M=map(int,input().split())
  A=[list(map(int,input().split())) for i in range(N)]
  ans=N
  s=set()
  for i in range(M-1):
    d=[0]*M
    for j in range(N):
      for k in range(M):
        if A[j][k]-1 in s:
          continue
        else:
          d[A[j][k]-1]+=1
          break
    ans=min(ans,max(d))
    s.add(d.index(max(d)))
  print(ans)
main()

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


n,m = list(map(int, input().split()))
a = [None]*n
d = [None]*n
from collections import Counter
for i in range(n):
    a[i] = list(map(lambda x: int(x)-1, input().split()))
    d[i] = a[i][0]

ans = float("inf")
used = [True] * m
num = m
while True:
    c = Counter(d)

    mv, mk = max((v,k) for k,v in c.items())

    ans = min(ans, mv)
    used[mk] = False
    num -= 1
    if num==0:
        break
    for i in range(n):
        if not used[d[i]]:
            for j in range(m):
                if used[a[i][j]]:
                    d[i] = a[i][j]
                    break
print(ans)

Solution (Python):
from collections import deque
from typing import Optional


class DeletableDeque:
    """Deletable Deque: a deque that supports lazy deletion of values."""

    __slots__ = ["_set", "_deque"]

    def __init__(self, *initial_values: int) -> None:
        self._set = set()
        self._deque = deque([])

        if initial_values:
            for v in initial_values:
                self.append(v)

    @property
    def topleft(self) -> Optional[int]:
        """Return the leftmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[0] not in self._set:
            self._deque.popleft()
        if not self._deque:
            return None
        return self._deque[0]

    def append(self, value: int) -> None:
        """Append value to the right side of the deque."""
        if value in self._set:
            return
        self._set.add(value)
        self._deque.append(value)

    def delete(self, value: int) -> None:
        """Delete value from the deque."""
        if value not in self._set:
            return
        self._set.discard(value)


def agc018_b():
    
    import sys
    from collections import Counter

    readline = sys.stdin.buffer.readline

    N, M = map(int, readline().split())
    A = [DeletableDeque(*map(int, readline().split())) for _ in range(N)]

    res = 301
    for _ in range(M):
        cnt = Counter(a.topleft for a in A)
        popular_sport = max(cnt, key=cnt.get)
        res = min(res, cnt[popular_sport])
        for a in A:
            a.delete(popular_sport)

    print(res)


if __name__ == "__main__":
    agc018_b()

Solution (Python):
from collections import deque
from typing import Optional


class DeletableDeque:
    """Deletable Deque: a deque that supports lazy deletion of values."""

    __slots__ = ["_set", "_deque"]

    def __init__(self, *initial_values: int) -> None:
        self._set = set()
        self._deque = deque([])

        if initial_values:
            for v in initial_values:
                self.append(v)

    @property
    def topleft(self) -> Optional[int]:
        """Return the leftmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[0] not in self._set:
            self._deque.popleft()
        if not self._deque:
            return None
        return self._deque[0]

    def append(self, value: int) -> None:
        """Append value to the right side of the deque."""
        if value in self._set:
            return
        self._set.add(value)
        self._deque.append(value)

    def delete(self, value: int) -> None:
        """Delete value from the deque."""
        if value not in self._set:
            return
        self._set.discard(value)


def agc018_b():
    
    import sys
    from collections import Counter

    readline = sys.stdin.buffer.readline

    N, M = map(int, readline().split())
    A = [DeletableDeque(*map(int, readline().split())) for _ in range(N)]

    res = 301
    for _ in range(M):
        cnt = Counter([a.topleft for a in A])
        popular_sport = max(cnt, key=cnt.get)
        res = min(res, cnt[popular_sport])
        for a in A:
            a.delete(popular_sport)

    print(res)


if __name__ == "__main__":
    agc018_b()

Solution (Python):
from collections import deque
from typing import Optional


class DeletableDeque:
    """Deletable Deque: a deque that supports lazy deletion of values."""

    __slots__ = ["_set", "_deque"]

    def __init__(self, *initial_values: int) -> None:
        self._set = set()
        self._deque = deque([])

        if initial_values:
            for v in initial_values:
                self.append(v)

    def __contains__(self, value: int) -> bool:
        return value in self._set

    def __len__(self) -> int:
        return len(self._set)

    @property
    def is_empty(self) -> bool:
        """Return whether the deque has no values or not."""
        return len(self) == 0

    @property
    def top(self) -> Optional[int]:
        """Return the rightmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[-1] not in self._set:
            self._deque.pop()
        if not self._deque:
            return None
        return self._deque[-1]

    @property
    def topleft(self) -> Optional[int]:
        """Return the leftmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[0] not in self._set:
            self._deque.popleft()
        if not self._deque:
            return None
        return self._deque[0]

    def pop(self) -> Optional[int]:
        """Pop and return the rightmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[-1] not in self._set:
            self._deque.pop()
        if not self._deque:
            return None
        res = self._deque.pop()
        self._set.discard(res)
        return res

    def popleft(self) -> Optional[int]:
        """Pop and return the leftmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[0] not in self._set:
            self._deque.popleft()
        if not self._deque:
            return None
        res = self._deque.popleft()
        self._set.discard(res)
        return res

    def append(self, value: int) -> None:
        """Append value to the right side of the deque."""
        if value in self._set:
            return
        self._set.add(value)
        self._deque.append(value)

    def appendleft(self, value: int) -> None:
        """Append value to the left side of the deque."""
        if value in self._set:
            return
        self._set.add(value)
        self._deque.appendleft(value)

    def delete(self, value: int) -> None:
        """Delete value from the deque."""
        if value not in self._set:
            return
        self._set.discard(value)


def agc018_b():
    
    import sys
    from collections import defaultdict

    readline = sys.stdin.buffer.readline

    N, M = map(int, readline().split())
    A = [DeletableDeque(*list(map(int, readline().split()))[::-1]) for _ in range(N)]

    res = 301
    for _ in range(M):
        cnt = defaultdict(int)
        for a in A:
            cnt[a.top] += 1

        popular_sport = max(cnt, key=cnt.get)
        res = min(res, cnt[popular_sport])
        for a in A:
            a.delete(popular_sport)

    print(res)


if __name__ == "__main__":
    agc018_b()

Solution (Python):
from collections import deque
from typing import Optional


class DeletableDeque:
    """Deletable Deque: a deque that supports lazy deletion of values."""

    __slots__ = ["_set", "_deque"]

    def __init__(self, *initial_values: int) -> None:
        self._set = set()
        self._deque = deque([])

        if initial_values:
            for v in initial_values:
                self.append(v)

    def __contains__(self, value: int) -> bool:
        return value in self._set

    def __len__(self) -> int:
        return len(self._set)

    @property
    def is_empty(self) -> bool:
        """Return whether the deque has no values or not."""
        return len(self) == 0

    @property
    def top(self) -> Optional[int]:
        """Return the rightmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[-1] not in self._set:
            self._deque.pop()
        if not self._deque:
            return None
        return self._deque[-1]

    @property
    def topleft(self) -> Optional[int]:
        """Return the leftmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[0] not in self._set:
            self._deque.popleft()
        if not self._deque:
            return None
        return self._deque[0]

    def pop(self) -> Optional[int]:
        """Pop and return the rightmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[-1] not in self._set:
            self._deque.pop()
        if not self._deque:
            return None
        res = self._deque.pop()
        self._set.discard(res)
        return res

    def popleft(self) -> Optional[int]:
        """Pop and return the leftmost value from the deque.
        If the deque is empty, None is returned.
        """
        while self._deque and self._deque[0] not in self._set:
            self._deque.popleft()
        if not self._deque:
            return None
        res = self._deque.popleft()
        self._set.discard(res)
        return res

    def append(self, value: int) -> None:
        """Append value to the right side of the deque."""
        if value in self._set:
            return
        self._set.add(value)
        self._deque.append(value)

    def appendleft(self, value: int) -> None:
        """Append value to the left side of the deque."""
        if value in self._set:
            return
        self._set.add(value)
        self._deque.appendleft(value)

    def delete(self, value: int) -> None:
        """Delete value from the deque."""
        if value not in self._set:
            return
        self._set.discard(value)


def agc018_b():
    
    import sys
    from collections import defaultdict

    readline = sys.stdin.buffer.readline

    N, M = map(int, readline().split())
    A = [DeletableDeque(*map(int, readline().split())) for _ in range(N)]

    res = 301
    for _ in range(M):
        cnt = defaultdict(int)
        for a in A:
            cnt[a.topleft] += 1

        popular_sport = max(cnt, key=cnt.get)
        res = min(res, cnt[popular_sport])
        for a in A:
            a.delete(popular_sport)

    print(res)


if __name__ == "__main__":
    agc018_b()

Solution (Python):
import collections

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

s = set()
for _ in range(M-1):
    count = [0]*M
    for i in range(N):
        for x in A[i]:
            if x in s:
                continue
            else:
                count[x-1] += 1
                break
    ans = min(ans, max(count))
    idx = count.index(max(count))
    s.add(idx + 1)

print(ans)

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

ans = n
used = set()
for i in range(m):
    count = [0]*(m+1)
    for j in range(n):
        count[a[j][-1]] += 1

    ans = min(max(count), ans)
    num = count.index(max(count))
    used.add(num)
    for j in range(n):
        while len(a[j]) > 0:
            if a[j][-1] in used:
                a[j].pop()
            else:
                break

print(ans)

Solution (Python):
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(500000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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


def check(dic):
    lst=[0]*m
    for i in range(n):
        for j in range(m):
            if dic[a[i][j]]==1:
                lst[a[i][j]-1]+=1
                break
    maxl=max(lst)
    
    if maxl==0:
        return n
    for i in range(m):
        if lst[i]==maxl:
            dic[i+1]=0
            break

    return min(maxl,check(dic))


dic={}
for i in range(m):
    dic[i+1]=1

print(check(dic))

Solution (Python):
n,m = map(int,input().split())
a = tuple([tuple(map(int,input().split())) for _ in range(n)])

ok = n
ng = 0
for _ in range(10):
    mid = (ok+ng)//2

    check = True
    inds = [0] * n
    done = [0] * (m+1)
    while(check):
        cnt_max = 0
        cnt = [0] * (m+1)
        for i in range(n):
            ind = inds[i]
            while(done[a[i][ind]] != 0):
                ind += 1
                if(ind == m):
                    check = False
                    break
            if(ind < m):
                inds[i] = ind
                cnt[a[i][ind]] += 1
                cnt_max = max(cnt_max, cnt[a[i][ind]])

        if(cnt_max <= mid):
            break

        for i in range(1,m+1):
            if(cnt[i] > mid):
                done[i] = 1

    if(check):
        ok = mid
    else:
        ng = mid

print(ok)

Solution (Python):
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, M = map(int, readline().split())
A = np.array(read().split(), np.int64)

A = A.reshape(N, M)

def f(A):
    if A.shape[1] == 0:
        return 10**9
    count = np.bincount(A[:, 0])
    n = count.max()
    i = count.argmax()
    A = A.ravel()
    A = A[A != i]
    A = A.reshape(N, -1)
    return min(n, f(A))

print(f(A))

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

def solve(bans):
    cnts=[0]*m
    for itm in a:
        for fav in itm:
            if (fav-1) in bans:
                continue
            cnts[fav-1]+=1
            break
    ret = max(cnts)
    max_ss = [i for i, v in enumerate(cnts) if v == ret]
    return ret, max_ss 

ban_s = []
ans=10000
while True:
    ret, max_ss = solve(ban_s)
    if ret==0:
        break
    ans=min(ans,ret)
    ban_s.extend(max_ss)

print(ans)

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

Solution (Python):
from collections import*
(n,m),*d=[list(map(int,o.split()))for o in open(0)]
r=range(a:=n)
for _ in[0]*m:
 k=[]
 for i in r:k+=d[i][0],
 I,w=Counter(k).most_common()[0];a=min(a,w)
 for j in r:d[j].remove(I)
print(a)

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

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




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

a=[[-1]*m for _ in range(n)]

for y in range(n):
    for x in range(m):
        a[y][aa[y][x]-1]=x

def pri(x):
    for item in x:
        print(item)

ans=301
for _ in range(m):
    score=[0]*m
    
    
    for y in range(n):
        mini=-1
        miniscore=501
        for x in range(m):
            if miniscore>a[y][x]:
                mini=x
                miniscore=a[y][x]
        score[mini]+=1
    tmp=max(score)
    ans=min(tmp,ans)
    
    for x in range(m):
        if score[x]==tmp:
            for y in range(n):
                a[y][x]=501

print(ans)

Solution (Python):

from collections import Counter
(n, m), *d = [list(map(int, o.split())) for o in open(0)]
a = n
for _ in [0] * m:
    k = []
    for i in range(n):
        k += d[i][0],
    ind, w = Counter(k).most_common()[0]
    a = min(a, w)
    for j in range(n):
        d[j].remove(ind)
print(a)

Solution (Python):

from collections import Counter
N, M = map(int, input().split())
data = [list(map(int, input().split())) for i in range(N)]
ans = N
for i in range(M):
    K = []
    for j in range(N):
        K.append(data[j][0])
    index, weight = Counter(K).most_common()[0]
    ans = min(ans, weight)
    for k in range(N):
        data[k].remove(index)
print(ans)