Problem:


Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

2 \leq N \leq 2\times 10^5

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

4 10
1 2
2 1
1 2
2 1
1 2
1 3
1 4
2 3
2 4
3 4

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3



Sample input:
5 3
1 2
3 4
5 1


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
n, m = map(int, input().split())

root = [-1]*n

def find(n):
    if root[n] < 0:
        return n
    else:
        return find(root[n])

def unite(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return
    else:
        root[x] += root[y]
        root[y] = x

def size(n):
    return -root[find(n)]

for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    unite(a, b)

ans = max(map(size, range(n)))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
n, m = map(int, input().split())

root = [-1]*n

def find(n):
    if root[n] < 0:
        return n
    else:
        return find(root[n])

def unite(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return
    else:
        root[x] += root[y]
        root[y] = x

for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    unite(a, b)

print(-min(root))

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
t = [-1*(i+1) for i in range(n)]
count = 0
for _ in range(m):
    a, b = map(lambda x: int(x) - 1, input().split())
    if t[a] <= -1 and t[b] <= -1:
        count += 1
        t[a] = count
        t[b] = count
        continue
    if t[a] > -1 and t[b] > -1 and t[a] != t[b]:
        max_t = max(t[a], t[b])
        min_t = min(t[a], t[b])
        t[a] = max_t
        t[b] = max_t
        t = list(map(lambda x: max_t if x == min_t else x, t))
        continue
    if t[a] > -1 and t[b] > -1 and t[a] == t[b]:
        continue
    if t[a] <= -1:
        t[a] = t[b]
        continue
    if t[b] <= -1:
        t[b] = t[a]

print(
    max([t.count(i) for i in set(t)])
)

Submission status: Time Limit Exceeded

Solution code:
import collections

n, m = map(int, input().split())
if m == 0:
    print(1)
    exit()
if m == 1:
    print(2)
    exit()
boss = {i: 0 for i in range(1, n + 1)}

def look_boss(num):
    if boss[num] == 0:
        return num
    while num != boss[num]:
        num = boss[num]
    return num

for _ in range(m):
    a, b = map(int, input().split())
    boss_a = look_boss(a)
    boss[a] = boss_a
    boss_b = look_boss(b)
    boss[b] = boss_b
    if boss_a != boss_b:
        boss[boss_b] = boss_a

count = [0]*(n+1)
for i in range(1, n+1):
    count[look_boss(i)] += 1
print(max(count))

Submission status: Time Limit Exceeded

Solution code:
"""
自分の解答
"""

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

if M == 0:
    print(1)
    exit()

R = [set(map(int, input().split(" "))) for i in range(M)]

groups = []
while len(R) > 0:
    r = R.pop()
    for r_ in R:
        if len(r & r_) > 0:
            r |= r_
    groups.append(r)

print(max(map(len, groups)))

Submission status: Time Limit Exceeded

Solution code:
def main():
    n, m, *ab, = map(int, open(0).read().split())
    p = [-1] * (n + 1)

    def find(x):
        while p[x] > 0:
            x = p[x]
        return x

    def union(i, j):
        pi, pj = find(i), find(j)
        if pi == pj:
            return
        if p[pi] < p[pj]:
            pi, pj = pj, pi
            i, j = j, i
        p[pi] += p[pj]
        p[pj] = pi
        #reconnect(j, pi)

    def reconnect(i, j):
        while p[i] > 0:
            k = p[i]
            p[i] = j
            i = k

    for i, j in zip(ab[::2], ab[1::2]):
        union(i, j)

    print(-min(p))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def S(): return input()
def LS(): return input().split()


class UnionFind():
    def __init__(self, n):
        self.n = n
        # 各要素の親要素 親は -(その集合の要素数)
        self.parents = [-1] * n

    def find(self, x):
        '''要素 x の親要素の番号を返す'''
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        '''要素 x が属する集合と要素 y が属する集合を併合する'''
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        '''要素 x が属する集合の要素数を返す'''
        return -self.parents[self.find(x)]

    def same(self, x, y):
        '''要素 x と要素 y が同じ集合に属するかを返す'''
        return self.find(x) == self.find(y)

    def members(self, x):
        '''要素 x が属する集合の要素をリストを返す'''
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def main():
    n, m = LI()
    uf = UnionFind(n)
    for _ in range(m):
        a, b, = LI()
        a, b = a-1, b-1
        uf.union(a, b)
    ans = 0
    for _, v in uf.all_group_members().items():
        ans = max(ans, len(v))
    print(ans)


main()

Submission status: Time Limit Exceeded

Solution code:
# @oj: atcoder
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-08-29 22:53
# @url:https://atcoder.jp/contests/abc177/tasks/abc177_d
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

BUFSIZE = 8192
sys.setrecursionlimit(10 ** 7)
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")
# ------------------------------
def main():
    n,m=map(int,input().split())
    pairs=[]
    for i in range(m):
        a,b=map(int,input().split())
        temp=[]
        temp.append(a)
        temp.append(b)
        pairs.append(temp)
    fa=[i for i in range(n+1)]
    def find(x):
        if x!=fa[x]:
            fa[x]=find(fa[x])
        return fa[x]
    def union(x,y):
        x = find(x)
        y = find(y)
        if x == y:  
            return
        fa[x] = y
    for (i,j) in pairs:
        union(i,j)
    for (i,j) in pairs:
        union(j,i)
    d=collections.Counter(fa)
    # print (fa)
    sd=sorted(d.items(),key=lambda x:x[1])
    # print (sd)
    if len(sd)>0:
        print (sd[-1][1])
    else:
        print (0)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# @oj: atcoder
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-08-29 22:53
# @url:https://atcoder.jp/contests/abc177/tasks/abc177_d
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio

BUFSIZE = 8192

BUFSIZE = 8192
sys.setrecursionlimit(10 ** 7)
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")
# ------------------------------
def main():
    n,m=map(int,input().split())
    pairs=[]
    for i in range(m):
        a,b=map(int,input().split())
        temp=[]
        temp.append(a)
        temp.append(b)
        pairs.append(temp)
    fa=[i for i in range(2*10**6+1)]
    def find(x):
        if x!=fa[x]:
            fa[x]=find(fa[x])
        return fa[x]
    def union(x,y):
        x = find(x)
        y = find(y)
        if x == y:  
            return
        fa[x] = y
    for (i,j) in pairs:
        union(i,j)
    for (i,j) in pairs:
        union(j,i)
    d=collections.Counter(fa)
    # print (fa)
    sd=sorted(d.items(),key=lambda x:x[1])
    # print (sd)
    if len(sd)>0:
        print (sd[-1][1])
    else:
        print (0)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
group_num = [i + 1 for i in range(n)]
cnt = [0] * n

def find(x, y):
    if group_num[x - 1] == group_num[y - 1]:
        return True
    else:
        return False

def union(x, y):
    for i in range(n):
        if group_num[i] == group_num[x - 1]:
            group_num[i] = group_num[y - 1]
    return

for i in range(m):
    a, b = map(int, input().split())
    if find(a, b):
        continue
    else:
        union(a, b)

for i in range(n):
    cnt[group_num[i] - 1] += 1

print(max(cnt))

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


#隣接リスト 1-index
def make_adjlist_nond(n, edges):
    res = [[] for _ in range(n+1)]
    for edge in edges:
        res[edge[0]].append(edge[1])
        res[edge[1]].append(edge[0])
    return res


def main():
    N, M = NMI()
    F = {}
    for _ in range(M):
        a, b = NMI()
        F[(a, b)] = 1
    tree = make_adjlist_nond(N, list(F.keys()))

    ans = 0
    for start in range(1, N+1):
        que = deque()
        que.append(start)
        seen = [0] * (N+1)
        seen[start] = 1
        fri_cnt = 1
        while que:
            now = que.popleft()

            for goto in tree[now]:
                if seen[goto]:
                    continue
                seen[goto] = 1
                fri_cnt += 1
                que.append(goto)
        ans = max(fri_cnt, ans)
    print(ans)





if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    n, m = map(int, input().split())
    ab = [[] for _ in range(n)]
    for _ in range(m):
        a, b = map(int, input().split())
        ab[a-1].append(b-1)
        ab[b-1].append(a-1)

    ans = 0
    n_set = deque([i for i in range(n)])
    while n_set:
        g = set()
        queue = deque([n_set.popleft()])
        while queue:
            now = queue.popleft()
            if now in g:
                continue
            g.add(now)
            for i in ab[now]:
                if i not in g:
                    queue.append(i)
                    g.add(i)
        ans = max(ans, len(g))
        n_set = deque(set(n_set) - g)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().strip().split())

groups = []

for _ in range(M):
	Ai, Bj = map(int, input().strip().split())

	g_ai = -1
	g_bj = -1

	for i, group in enumerate(groups):
		if Ai in group:
			g_ai = i
		if Bj in group:
			g_bj = i

	if g_ai > -1 and g_bj > -1:
		new_g = groups[g_ai] | groups[g_bj]
		groups.append(new_g)
		groups[g_ai] = set()
		groups[g_bj] = set()

	if g_ai < 0 and g_bj < 0:
		new_g = set([Ai, Bj])
		groups.append(new_g)

	if g_ai < 0 and g_bj > -1:
		groups[g_bj].add(Ai)

	if g_ai > -1 and g_bj < 0:
		groups[g_ai].add(Bj)

if not groups:
	print(1)
else:
	print(max([len(g) for g in groups]))

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
groups = [x for x in range(n)]
count = [0]*n

def UnionFind(x):
    while x != groups[x]:
        x = groups[x]
    return x

for _ in range(m):
    x, y = map(int, input().split())
    x, y = UnionFind(x-1), UnionFind(y-1)
    if x != y:
        groups[y] = x

for i in range(n):
    count[UnionFind(i)] += 1
print(max(count))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    n, m = map(int, input().split())
    ab = [[] for _ in range(n)]
    for _ in range(m):
        a, b = map(int, input().split())
        ab[a-1].append(b-1)
        ab[b-1].append(a-1)

    ans = 0
    n_set = deque([i for i in range(n)])
    while n_set:
        g = set()
        queue = deque([n_set.popleft()])
        while queue:
            now = queue.popleft()
            if now in g:
                continue
            g.add(now)
            for i in ab[now]:
                queue.append(i)
                g.add(i)
        ans = max(ans, len(g))
        n_set = deque(set(n_set) - g)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


#隣接リスト 1-index
def make_adjlist_nond(n, edges):
    res = [[] for _ in range(n+1)]
    for edge in edges:
        res[edge[0]].append(edge[1])
        res[edge[1]].append(edge[0])
    return res


def main():
    N, M = NMI()
    F = [NLI() for _ in range(M)]
    tree = make_adjlist_nond(N, F)
    
    ans = 0
    for start in range(1, N+1):
        que = deque()
        que.append(start)
        seen = [0] * (N+1)
        seen[start] = 1
        fri_cnt = 1
        while que:
            now = que.popleft()

            for goto in tree[now]:
                if seen[goto]:
                    continue
                seen[goto] = 1
                fri_cnt += 1
                que.append(goto)
        ans = max(fri_cnt, ans)
    print(ans)





if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    sys.setrecursionlimit(100000)
    n, m, *ab, = map(int, open(0).read().split())

    p = [-1] * (n + 1)

    def f(x):
        if p[x] < 0:
            return x
        else:
            return f(p[x])

    def g(x, t):
        if p[x] < 0:
            return
        nx = p[x]
        p[x] = t
        g(nx, t)
        

    ans = -1
    order = set()
    for i, j in zip(ab[::2], ab[1::2]):
        if i > j:
            i, j = j, i
        if (i, j) in order:
            continue

        pi, pj = f(i), f(j)
        if pi == pj:
            continue
        p[pi] += p[pj]
        ans = min(ans, p[pi])
        p[j] = pi
        p[pj] = pi
        g(j, pi)
        order.add((i, j))
    print(-ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
if M == 0:
  print(1)
else:
  F = list((sorted(map(int,input().split()))) for i in range(M))
  L = list(map(list,set(map(tuple,F))))
  
  team = []
  for i in range(len(L)):
    if i == 0:
      team.append(L[i])
    else:
      for j in range(len(team)):
        if L[i][0] in team[j] and L[i][1] not in team[j]:
          team[j].append(L[i][1])
          break
        elif L[i][0] not in team[j] and L[i][1] in team[j]:
          team[j].append(L[i][0])
          break
      else:
        team.append(L[i])
  team_l = [len(k) for k in team]
  print(max(team_l))

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    sys.setrecursionlimit(100000)
    n, m, *ab, = map(int, open(0).read().split())

    p = [-1] * (n + 1)

    def f(x):
        if p[x] < 0:
            return x
        else:
            return f(p[x])

    ans = -1
    order = set()
    for i, j in zip(ab[::2], ab[1::2]):
        if i > j:
            i, j = j, i
        if (i, j) in order:
            continue

        pi, pj = f(i), f(j)
        if pi == pj:
            continue
        p[pi] += p[pj]
        ans = min(ans, p[pi])
        p[j] = pi
        p[pj] = pi
        order.add((i, j))
    print(-ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    sys.setrecursionlimit(100000)
    n, m, *ab, = map(int, open(0).read().split())

    p = [-1] * (n + 1)

    def f(x):
        if p[x] < 0:
            return x
        else:
            return f(p[x])

    ans = -1
    for i, j in zip(ab[::2], ab[1::2]):
        if i > j:
            i, j = j, i

        pi, pj = f(i), f(j)
        if pi == pj:
            continue
        p[pi] += p[pj]
        ans = min(ans, p[pi])
        p[j] = pi
        p[pj] = pi

    print(-ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
N, M = map(int, input().split())
if M == 0:
    print(1)
else:
    count = 0
    Info = []
    while count < M:
        A, B = map(int,input().split())
        I = {A,B}
        flag = True
        for J in Info:
            if len(I.intersection(J)) != 0:
                k = Info.index(J)
                Info[k] = I.union(J)
                flag = False
                break
        if flag == True:
            Info += [I]
        count += 1
    print(max(len(K) for K in Info))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)

n, m = map(int, input().split())

root = [-1] * n


def r(x):
    if root[x] < 0:
        return x

    return r(root[x])


def unite(x, y):
    x = r(x)
    y = r(y)
    if x == y:
        return
    root[x] += root[y]
    root[y] = x


def size(x):
    return -1 * root[r(x)]


for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    unite(a, b)

ans = 0
for i in range(n):
    ans = max(ans, size(i))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from collections import deque

n, m = map(lambda x: int(x), input().split())
person_to_friends = defaultdict(set)

for _ in range(m):
    a, b = map(lambda x: int(x), input().split())
    person_to_friends[a].add(b)
    person_to_friends[b].add(a)

not_searched = set(range(1, n+1))
max_pool_num = 1

while len(not_searched) > 0:
#     print(not_searched)
    first_person = not_searched.pop()
    friend_pool = set([first_person])
    que = deque([first_person])
    while len(que) > 0:
        current_person = que.popleft()
        not_searched_friends = person_to_friends[current_person].intersection(not_searched)
#         print(not_searched_friends)
        for friend in not_searched_friends:
            not_searched.remove(friend)
            que.append(friend)
            friend_pool.add(friend)
    max_pool_num = max(len(friend_pool), max_pool_num)
print(max_pool_num)

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split())
mem=[[] for i in range(N)]
for i in range(M):
    a,b=map(int,input().split())
    if b-1 not in mem[a-1]:
        mem[a-1].append(b-1)
    if a-1 not in mem[b-1]:
        mem[b-1].append(a-1)


ans=0
vist=[0]*N

for i in range(N):
    if vist[i]==1:
        continue
    hq=[i]
    cnt=1
    while hq:
        node=hq.pop()
        vist[node]=1
        for next in mem[node]:
            if vist[next]!=1:
                hq.append(next)
                if vist[next]!=2:
                    cnt+=1
                    vist[next]=2
        #print(hq,d)        
                
    ans=max(cnt,ans)
    #print(ans)
            
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
class Node:
    def __init__(self):
        self.friends = {}
        self.checked = False
    def add(self, b):
        self.friends[b] = True
N, M = [int(i) for i in input().split()]
P = [Node() for i in range(N)]
for i in range(M):
    A, B = [int(i)-1 for i in input().split()]
    P[A].add(B)
    P[B].add(A)

maxl = 0
for i in range(N):
    if P[i].checked == False:
        d = deque([i])
    else:
        continue
    counter = 0
    while d:
        q = d.popleft()
        counter += 1
        P[q].checked = True
        for key in P[q].friends.keys():
            if P[key].checked == False:
                d.append(key)
                P[key].checked = True
            for j in P[key].friends.keys():
                if P[j].checked == False:
                    d.append(j)
                    P[j].checked = True
    if maxl < counter:
        maxl = counter
print(maxl)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import defaultdict
    n, m, *ab, = map(int, open(0).read().split())
    f = defaultdict(lambda: set())
    for i, j in zip(ab[::2], ab[1::2]):
        f[i].add(j)
        f[j].add(i)

    group = []
    i = 1
    g = {i}
    nx = {i}
    checked = set()
    while i <= n:
        if i in checked:
            i += 1
            continue
        checked |= g
        tmp = set()
        for j in list(nx):
            tmp |= f[j]
        tmp -= checked

        if len(tmp) == 0:
            group.append(g)
            i += 1
            g = {i}
            continue
        else:
            g |= tmp
            nx = tmp

    ans = max(list(map(len, group)))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
N, M = (int(i) for i in input().split())
graph = csr_matrix((N, N), dtype=int)
for i in range(M):
    A, B = (int(i) for i in input().split())
    graph[A-1, B-1] = 1
    graph[B-1, A-1] = 1
_, labels = connected_components(
    csgraph=graph,
    directed=False,
    return_labels=True)
print(max(np.bincount(labels)))

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
if m == 0:
    ans = 1
else:
  a = []
  b = []
  for i in range(m):
    aa, bb = input().split()
    a.append(aa)
    b.append(bb)
  f1 = []
  f1.append(a[0])
  for i in range(m):
    if a[i] in f1:
        if not(b[i] in f1):
          f1.append(b[i])
    elif b[i] in f1:
        if not(a[i] in f1):
          f1.append(a[i])
  ans = len(f1)
  j = 1
  while j < m:
    f2 = []
    if a[j] in f1 or b[j] in f1:
        j += 1
        continue
    if j < m:
      f2.append(a[j])
      f1.append(a[j])
      for k in range(j, m):
        if a[k] in f2:
          f2.append(b[k])
          f1.append(b[k])
        elif b[k] in f2:
          f2.append(a[k])
          f1.append(a[k])
      rans = len(f2)
      if rans > ans:
        ans = rans
    j += 1
print (ans)

Submission status: Time Limit Exceeded

Solution code:
import collections

n, m = map(int, input().split())
ab = [(i+1) for i in range(n)]
for i in range(m):
  a, b = map(int, input().split())
  change = ab[b-1]
  ab[b-1] = a
  for j in range(n):
    if ab[j] == change:
      ab[j] = a
  #print(ab)
c = collections.Counter(ab)
num = c.most_common()[0][1]
print(num)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import connected_components
N, M = (int(i) for i in input().split())
graph = lil_matrix((N, N), dtype=int)
for i in range(M):
    A, B = (int(i) for i in input().split())
    graph[A-1, B-1] = 1
    graph[B-1, A-1] = 1
_, labels = connected_components(
    csgraph=graph,
    directed=False,
    return_labels=True)
print(max(np.bincount(labels)))

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
F = list(sorted(list(map(int,input().split()))) for i in range(M))
L = []
for i in F:
  if i not in L:
    L.append(i)
team = [0] * N
for t in L:
  team[t[0]-1] += 1
  team[t[1]-1] += 1
print(max(team)+1)

Submission status: Time Limit Exceeded

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def max_groups(self):
        max_groups = 1
        for x in self.roots():
            max_groups = max(max_groups, len(self.members(x)))
        return max_groups

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
    

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

uf = UnionFind(N)
for _ in range(M):
    a, b = list(map(int, input().split(" ")))
    uf.union(a - 1, b - 1)


print(uf.max_groups())

Submission status: Time Limit Exceeded

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N, M = list(map(int, input().split()))
u = UnionFind(N)
for _ in range(M):
    a, b = list(map(int, input().split()))
    u.union(a-1,b-1)

print(max([len(one) for one in list(u.all_group_members().values())]))