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: Runtime Error

Solution code:
import sys, io, os, re
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from pprint import pprint
from math import sin, cos, pi, radians, sqrt, floor, ceil
from copy import copy, deepcopy
from collections import deque, defaultdict
from fractions import gcd
from functools import reduce
from itertools import groupby, combinations
from heapq import heapify, heappush, heappop

# sys.setrecursionlimit(5000)

n1 = lambda: int(sys.stdin.readline().strip())
nn = lambda: list(map(int, sys.stdin.readline().strip().split()))
f1 = lambda: float(sys.stdin.readline().strip())
fn = lambda: list(map(float, sys.stdin.readline().strip().split()))
s1 = lambda: sys.stdin.readline().strip()
sn = lambda: list(sys.stdin.readline().strip().split())
nl = lambda n: [n1() for _ in range(n)]
fl = lambda n: [f1() for _ in range(n)]
sl = lambda n: [s1() for _ in range(n)]
nm = lambda n: [nn() for _ in range(n)]
fm = lambda n: [fn() for _ in range(n)]
sm = lambda n: [sn() for _ in range(n)]

def array1(n, d=0): return [d] * n
def array2(n, m, d=0): return [[d] * m for x in range(n)]
def array3(n, m, l, d=0): return [[[d] * l for y in xrange(m)] for x in xrange(n)]
def linc(A, d=1): return list(map(lambda x: x + d, A))
def ldec(A, d=1): return list(map(lambda x: x - d, A))

N, M = nn()
T = nm(M)

d = defaultdict(list)

"""
def st(x, y):
    if x < y:
        return (x, y)
    return (y, x)
"""

memo = array2(N+1, N+1)

for i in range(M):
    a, b = T[i]
    if memo[a][b] == 1:
        continue
    else:
        d[a].append(b); memo[a][b] = 1
        d[b].append(a); memo[b][a] = 1

ans = 0
for k, v in d.items():
    #print(k, v, len(v))
    tmp = len(v)
    if tmp > ans:
        ans = tmp

print(ans+1)

Submission status: Runtime Error

Solution code:
import numpy as np
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix
import collections

N, M = map(int, input().split())
edge = np.array([input().split() for _ in range(M)], dtype=np.int8).T

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

    tmp = np.ones(M, dtype=np.int8).T
    graph = csr_matrix((tmp, (edge[:] - 1)), (N, N))

    n, labels = connected_components(graph)

    c = collections.Counter(labels)

    print(max(c.values()))

Submission status: Runtime Error

Solution code:
N,M=map(int,input().split())
group=[]
number=[0 for i in range(N)]
A,B=map(int,input().split())
group.append([A,B])
number[0]=2


for i in range(M-1):
    A,B=map(int,input().split())
    flag=0
    for j in range(len(group)):
        new=[]
        if A in group[j]:
            flag=1
            if B not in group[j]:
                group[j].append(B)
                number[j]+=1
        elif B in group[j]:
            flag=1
            if A not in group[j]:
                group[j].append(A)
                number[j]+=1
                flag=1
    if flag==0:
        group.append([A,B])
        number[len(group)]=2

print(max(number))

Submission status: Runtime Error

Solution code:
def main():

    n,m = map(int,input().split())
    ary = []
    for i in range(m):
        aa, bb = map(int,input().split())
        l = min(aa,bb)
        r = max(aa,bb)
        ary.append((l,r))
    ary_s = list(set(ary))
    a = []
    # b = []
    for i in range(len(ary_s)):
        a.append(ary_s[i][0])
        a.append(ary_s[i][1])

    import collections
    c_a = collections.Counter(a).most_common()[0][1]
    print(c_a+1)
if __name__=='__main__':
    main()

Submission status: Runtime Error

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

from collections import defaultdict

par=[i for i in range(n)]
ro=defaultdict(int)
for i in range(n):
    ro[i]=1
def root(i):
    if par[i]==i:
        return i
    else:
        return root(par[i])

def unite(x,y):
    rx=root(x)
    ry=root(y)
    if rx!=ry:
        par[rx]=ry
        ro[ry]+=ro[rx]
        ro[rx]=0

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


# for i in range(n):
#     ro[root(i)]+=1

print(max(ro.values()))

Submission status: Runtime Error

Solution code:
import collections
n,m = map(int,input().split())
g = [-1]*n
for i in range(m):
  a,b = map(int,input().split())
  if g[a-1]!=-1:
    g[b-1] = g[a-1]
  elif g[b-1]!=-1:
    g[a-1] = g[b-1]
  else:
    g[a-1] = i
    g[b-1] = i
c = collections.Counter(g)
cnt = c.most_common()
if cnt[0][0]==-1:
  print (cnt[1][1])
else:
  print (cnt[0][1])

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
a = [set(map(int, input().split())) for i in range(m)]
b = []
for i in range(m):
  for j in range(i+1, m):
    if len(a[i] & a[j]) > 0:
      b.append(len(a[i] | a[j]))
print(max(b))

Submission status: Runtime Error

Solution code:
from collections import Counter
n, m = map(int, input().split())
ab = [tuple(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n)]
visited = [-1] * n
for a, b in ab:
    a, b = a-1, b-1
    g[a].append(b)
    g[b].append(a)
# print(g)
def dfs(start):
    global visited
    if visited[start] != -1:
        return 
    stack = []
    stack.append(start)
    visited[start] = start
    while stack:
        root = stack.pop()
        for j in g[root]:
            if visited[j] == -1:
                visited[j] = start
                stack.append(j)

for i in range(n):
    dfs(i)
# print(visited)
tmp = Counter(visited)
# print(tmp)
p = sorted([v for i, v in tmp.items() if v != 1])
island = len(p)
# print(island)
if island == 1:
    print(n)
else:
    print(p[-1])

Submission status: Runtime Error

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

color = []
colorStorage = []
for i in range(N):
    color.append(i)
    colorStorage.append([i])

for _ in range(M):
    p,q = map(int,input().split())
    p -= 1
    q -= 1
    if color[p] == color[q]:
        continue
    else:
        x = color[p]
        y = color[q]
        if len(colorStorage[x]) >= len(colorStorage[y]):
            for elem in colorStorage[y]:
                color[elem] = x
                colorStorage[x].append(elem)
            colorStorage[y] = []
        else:
            for elem in colorStorage[y]:
                color[elem] = y
                colorStorage[y].append(elem)
            colorStorage[x] = []
maxL = 0
for colorList in colorStorage:
    if maxL < len(colorList):
        maxL = colorList
print(maxL)

Submission status: Runtime Error

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

fMap = {}
count = 0
lister = []

for i in range(m):
    a, b = map(int, input().split())
    if a in fMap:
        if not b in fMap:
            lister[fMap[a]].append(b)
        else:
            if fMap[a] != fMap[b]:
                de = fMap[b]
                lB = lister[fMap[b]]
                for e in lB:
                    lister[fMap[a]].append(e)
                    fMap[e] = fMap[a]
                del lister[de]
        fMap[b] = fMap[a]
    elif b in fMap:
        if not a in fMap:
            lister[fMap[b]].append(a)
        fMap[a] = fMap[b]
    else:
        fMap[a] = count
        fMap[b] = count
        count+=1
        lister.append([a, b])

maxL = 0
for l in lister:
    if len(l) > maxL:
        maxL = len(l)
print(maxL)

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

D = defaultdict(set)
R = {}
for _ in range(M):
  a, b = map(int, input().split())
  if a in R:
    if b in R:
      aa, bb = R[a], R[b] 
      if aa == bb:
        pass
      else:
        for x in D[bb]:
          R[x] = aa
        D[aa] |= D[bb]
        del D[bb]
    else:
      R[b] = R[a]
      D[R[a]].add(b)
  else:
    if b in R:
      R[a] = R[b]
      D[R[b]].add(a)
    else:
      R[a] = a
      R[b] = a
      D[a].add(b)

print(max(len(x) for x in D.values()) + 1)

Submission status: Runtime Error

Solution code:
#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline


import collections,sys,threading
sys.setrecursionlimit(10**9)
threading.stack_size(10**8)






########################################
def solve():
	n , m = map(int , input().split())
	dic = defaultdict(set)
	for ii in range(m):
		u,v = map(int , input().split())
		dic[u].add(v)
		dic[v].add(u)
	l = []
	visited = [0]*(n+1)
	def f(node):
		visited[node] = True
		if len(dic[node]) == 1:
			return 1
		temp = 1
		for nei in dic[node]:
			if not visited[nei]:
				temp += f(nei)
				#print("?",node, nei , temp)
		return temp
	for i in range(1,n+1):
		if not visited[i]:
			l.append(f(i))
	#print(dic)
	#print(l)
	print(max(l))


threading.Thread(target=solve).start()

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
index = 1
group = [0] * (n + 1) # 何番目のグループにいるか
groups = [set()] # グループ
for i in range(m):
  a, b = map(int, input().split())
  _a = group[a]
  _b = group[b]
  if _a == 0 and _b == 0:
    group[a] = index
    group[b] = index
    groups.append({a,b})
    index += 1
  elif _a == 0:
    group[a] = _b
    groups[_b].add(a)
  elif _b == 0:
    group[b] = _a
    groups[_a].add(b)
  elif _a != _b:
    # 番号の若いほうへ
    if _a < _b: # bを移行
      for m in groups[b]:
        group[m] = _a
      groups[_a] = groups[_a] | groups[_b]
      groups[_b] = {}
    else:
      for m in groups[a]:
        group[m] = _b
      groups[_b] = groups[_a] | groups[_b]
      groups[_a] = {}
ans = max(map(lambda group: len(group), groups))
print(ans)

Submission status: Runtime Error

Solution code:
N,M = int(input())
print(N)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import networkx as nx

def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    G=nx.Graph()

    for a, b in zip(A,B):
        G.add_edge(a, b)

    Gc = max(nx.connected_components(G), key=len)
    print(len(Gc))
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

friends = [[0] * n for i in range(n)]

for i in range(m):
  a,b = map(int, input().split())
  friends[a-1][b-1] = 1
  friends[b-1][a-1] = 1
  
ans = 0
for i in friends:
  if sum(i) > ans:
    ans = sum(i)
    
print(ans+1)

Submission status: Runtime Error

Solution code:
# Python program to print connected 
# components in an undirected graph 
class Graph: 
	
	# init function to declare class variables 
	def __init__(self,V): 
		self.V = V 
		self.adj = [[] for i in range(V)] 

	def DFSUtil(self, temp, v, visited): 

		# Mark the current vertex as visited 
		visited[v] = True

		# Store the vertex to list 
		temp.append(v) 

		# Repeat for all vertices adjacent 
		# to this vertex v 
		for i in self.adj[v]: 
			if visited[i] == False: 
				
				# Update the list 
				temp = self.DFSUtil(temp, i, visited) 
		return temp 

	# method to add an undirected edge 
	def addEdge(self, v, w): 
		self.adj[v].append(w) 
		self.adj[w].append(v) 

	# Method to retrieve connected components 
	# in an undirected graph 
	def connectedComponents(self): 
		visited = [] 
		cc = [] 
		for i in range(self.V): 
			visited.append(False) 
		for v in range(self.V): 
			if visited[v] == False: 
				temp = [] 
				cc.append(self.DFSUtil(temp, v, visited)) 
		return cc 

n,m = map(int,input().split())
g = Graph(n); 
for i in range(m):
    a,b = map(int,input().split())
    g.addEdge(a-1,b-1) 
    cc = g.connectedComponents()

ans = 0
for i in cc:
    ans = max(ans,len(i))
print(ans)
# This code is contributed by Abhishek Valsan

Submission status: Runtime Error

Solution code:
import numpy as np
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix
import collections

N,M = map(int,input().split())
if M == 0:
    print(N)
else:
    edge = np.array([input().split() for _ in range(M)], dtype = np.int8).T
    tmp = np.ones(M, dtype = np.int8).T
    graph = csr_matrix((tmp, (edge[:] -1)), (N, N))

    n, labels = connected_components(graph,directed = False, connection = 'weak')

    c = collections.Counter(labels)

    print(max(c.values()))

Submission status: Runtime Error

Solution code:
import collections
N,M = map(int,input().split())
a = []
for i in range(M):
  a.append(sorted(list(map(int,input().split()))))
  
def get_unique_list(seq):
    seen = []
    return [x for x in seq if x not in seen and not seen.append(x)]

k = get_unique_list(a)
flat_list = []
original_list = k
for l in original_list:
  for item in l:
    flat_list.append(item)
s = collections.Counter(flat_list)
print(s.most_common()[0][1]+1)

Submission status: Runtime Error

Solution code:
#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"

input = sys.stdin.readline

########################################
n , m = map(int , input().split())
dic = defaultdict(set)
for ii in range(m):
	u,v = map(int , input().split())
	dic[u].add(v)
	dic[v].add(u)
l = []
visited = [0]*(n+1)
def f(node):
	visited[node] = True
	if len(dic[node]) == 1:
		return 1
	temp = 1
	for nei in dic[node]:
		if not visited[nei]:
			temp += f(nei)
			#print("?",node, nei , temp)
	return temp
for i in range(1,n+1):
	if not visited[i]:
		l.append(f(i))
#print(dic)
#print(l)
print(max(l))

Submission status: Runtime Error

Solution code:
from collections import defaultdict

def DFS(G,v,seen=None,path=None):
    if seen is None: seen = []
    if path is None: path = [v]

    seen.append(v)

    paths = []
    for t in G[v]:
        if t not in seen:
            t_path = path + [t]
            paths.append(tuple(t_path))
            paths.extend(DFS(G, t, seen[:], t_path))
    return paths
N, M = map(int,input().split())
# Build graph dictionary
G = defaultdict(list)
for _ in range(M):
  s, t = input().split()
  G[s].append(t)
  G[t].append(s)

# Run DFS, compute metrics
all_paths = [p for ps in [DFS(G, n) for n in set(G)] for p in ps]
max_len   = max(len(p) for p in all_paths)
print(max_len)

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

color = [None] * (n + 1)
for i in range(n + 1):
    color[i] = i

def root(x):
    global color

    if color[x] == x:
        return x
    return root(color[x])

def unite(x, y):
    rx = root(x)
    ry = root(y)
    if rx == ry:
        return
    color[rx] = ry

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

cnt = defaultdict(int)
for i in range(n):
    cnt[root(i + 1)] += 1
print(max(cnt.values()))

Submission status: Runtime Error

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

    person = [-1 for _ in range(N)]
    group_counter = 0
    menber_counter = []

    for _ in range(M):
        A, B = map(int, input().split())
        A -= 1
        B -= 1
        if person[A] == -1 and person[B] == -1:
            person[A] = group_counter
            person[B] = group_counter
            menber_counter.append(2)
            group_counter += 1
        elif person[A] != -1:
            current_group = person[A]
            if person[B] == current_group:
                continue
            person[B] = current_group
            menber_counter[current_group] += 1
        else:
            current_group = person[B]
            if person[A] == current_group:
                continue
            person[A] = current_group
            menber_counter[current_group] += 1
    print(max(menber_counter))

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
import sys
import collections
input = lambda: sys.stdin.readline().rstrip("\r\n")

class DFS:

    def __init__(self):
        self.adj = collections.defaultdict(list)
        self.ans = 0

    def addEdge(self, u, v):
        self.adj[u].append(v)
        self.adj[v].append(u)

    def dfs_helper(self, src, visited):
        self.ans += 1
        visited[src] = True
        for i in self.adj[src]:
            if not visited[i]:
                self.dfs_helper(i, visited)

    def dfs(self, src):
        res = - 10 ** 10
        visited = collections.defaultdict(lambda: False)
        for k, v in self.adj.items():
            visited[k] = False
        for k, v in self.adj.items():
            if not visited[k]:
                self.dfs_helper(k, visited)
                res = max(res, self.ans)
                self.ans = 0
        return res


def solve():
    d = DFS()
    n, m = map(int, input().split())
    for _ in range(m):
        u, v = map(int, input().split())
        d.addEdge(u, v)
    print(d.dfs(1))

solve()

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
a = [set(map(int, input().split())) for i in range(m)]
b = []
for i in range(m):
  for j in range(i+1, m):
    if a[i] & a[j]:
      b.append(len(a[i] | a[j]))
print(max(b))

Submission status: Runtime Error

Solution code:

# Python3 program to implement Disjoint Set Data 
# Structure. 
  
class DisjSet: 
    def __init__(self, n): 
        # Constructor to create and 
        # initialize sets of n items 
        self.rank = [1] * n 
        self.parent = [i for i in range(n)] 
  
  
    # Finds set of given item x 
    def find(self, x): 
          
        # Finds the representative of the set 
        # that x is an element of 
        if (self.parent[x] != x): 
              
            # if x is not the parent of itself 
            # Then x is not the representative of 
            # its set, 
            self.parent[x] = self.find(self.parent[x]) 
              
            # so we recursively call Find on its parent 
            # and move i's node directly under the 
            # representative of this set 
  
        return self.parent[x] 
  
  
    # Do union of two sets represented 
    # by x and y. 
    def Union(self, x, y): 
          
        # Find current sets of x and y 
        xset = self.find(x) 
        yset = self.find(y) 
  
        # If they are already in same set 
        if xset == yset: 
            return
  
        # Put smaller ranked item under 
        # bigger ranked item if ranks are 
        # different 
        if self.rank[xset] < self.rank[yset]: 
            self.parent[xset] = yset 
  
        elif self.rank[xset] > self.rank[yset]: 
            self.parent[yset] = xset 
  
        # If ranks are same, then move y under 
        # x (doesn't matter which one goes where) 
        # and increment rank of x's tree 
        else: 
            self.parent[yset] = xset 
            self.rank[xset] = self.rank[xset] + 1
  
# Driver code 
'''obj = DisjSet(5) 
obj.Union(0, 2) 
obj.Union(4, 2) 
obj.Union(3, 1) 
if obj.find(4) == obj.find(0): 
    print('Yes') '''
n,m=map(int,input().split())
obj = DisjSet(n+1)
for i in range(m):
    a,b=map(int,input().split())
    obj.Union(a,b) 
c=0
l1=[0]*n
for i in range(1,n+1):
    l1[obj.find(i)]+=1
print(max(l1))

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())
a,b = map(int,input().split())
sets = [set([a,b])]
for i in range(m-1):
  a,b = map(int,input().split())
  for s in sets:
    if (a in s) or (b in s):
      s.add(a)
      s.add(b)
      break
    else:
      sets.append(set([a,b]))
ans = 0
print(sets)
for s in sets:
  ans = max(ans,len(s))
print(ans)

Submission status: Runtime Error

Solution code:
for i in range(n):
    nm[i]=list(set(nm[i]))
visited=[0]*(n+1)
count=0
for i in range(n):
    if visited[i]==0:
        stack=[]
        stack.append(i)
        visited[i]+=1
        temp=1
        while stack:
            x=stack.pop()
            
            for j in nm[x]:
                if visited[j]==0:
                    visited[j]+=1
                    stack.append(j)
                    temp+=1
        count=max(temp,count)
print(count)

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
c = []
for _ in range(m):
    a, b = map(int, input().split())
    for i in c:
        if a in i or b in i:
            i.add(a)
            i.add(b)
    else:
        c.append(set())
        c[-1].add(a)
        c[-1].add(b)
print(max(map(len, c)))

Submission status: Runtime Error

Solution code:
from collections import defaultdict


def main():
    people_count, info_count = [int(x) for x in input().split()]
    frieds_circle_ids = [-1] * people_count
    id_counter = defaultdict(int)
    new_id = 0
    for _ in range(info_count):
        a, b = [int(x) - 1 for x in input().split()]
        id_a = frieds_circle_ids[a]
        id_b = frieds_circle_ids[b]
        if id_a == -1 == id_b:
            frieds_circle_ids[a] = new_id
            frieds_circle_ids[b] = new_id
            id_counter[new_id] += 2
            new_id += 1
        elif id_a == -1:
            frieds_circle_ids[a] = id_b
            id_counter[id_b] += 1
        elif id_b == -1:
            frieds_circle_ids[b] = id_a
            id_counter[id_a] += 1
        else:
            pass
    return max(count for count in id_counter.values())


if __name__ == '__main__':
    print(main())

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)
def input(): return sys.stdin.readline().rstrip()


def main():
    n, m = map(int, input().split())
    l = {}
    for _ in range(m-1):
        a, b = sorted(map(int, input().split()))
        if a not in l:
            l[a] = {b}
        else:
            l[a].add(b)
    i = max(l, key=lambda k: len(l[k]))
    print(len(l[i]) + 1)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

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

G = list()
G.append({a1, b1})
for i in range(1, M):
  ai, bi = map(int, readline().split())
  for j in G:
    if ai in j or bi in j:
      j.add(ai)
      j.add(bi)
    else:
      G.append({ai, bi})
print(len(max(G)))

Submission status: Runtime Error

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

N, M = map(int, input().split())
UF = [-1] * (N+1)
def find(x):
    global UF
    if UF[x] == -1:
        return x
    else:
        UF[x] = find(UF[x])
        return UF[x]
def union(x,y):
    global UF
    xx = find(x)
    yy = find(y)
    if UF[x] == UF[y] == -1:
        UF[y] = xx
        return
    elif xx == yy:
        return 
    else:
        UF[yy] = xx
        return 
    
for _ in range(M):
    x, y = map(int, input().split())
    union(x,y)
    
cnt = [0] * (N+1)

for i in range(1,N+1):
    z = find(i)
    cnt[z] += 1

print(max(cnt))

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
parent = [i for i in range(n)]
root_list = [None for _ in range(n)]
element_count = [0 for _ in range(n)]


def root(x):
    while parent[x] != x:
        x = parent[x]
    return x


for i in range(m):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    parent[root(b)] = root(a)


def set_root(x):
    if root_list[x] is not None:
        return root_list[x]
    if parent[x] == x:
        root_list[x] = x
        return x
    else:
        x_root = set_root(parent[x])
        root_list[x] = x_root
        return x_root


for i in range(n):
    set_root(i)
for i in range(n):
    x_root = root_list[i]
    element_count[x_root] += 1

print(max(element_count))

Submission status: Runtime Error

Solution code:
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
input = sys.stdin.readline
INF = float("inf")


def dfs(G, visited, v, cnt):
    visited[v] = True

    for nv in G[v]:
        if visited[nv]:
            continue
        cnt = dfs(G, visited, nv, cnt + 1)
    
    return cnt


# 処理内容
def main():
    N, M = map(int, input().split())

    if M == 0:
        print(1)
        return

    P = set()
    for _ in range(M):
        a, b = map(int, input().split())
        a -= 1; b -= 1
        if a > b:
            a, b = b, a
        P.add((a, b))

    G = [[] for _ in range(N)]
    for pair in P:
        a, b = pair
        G[a].append(b)
        G[b].append(a)

    visited = [False] * N
    ans = 1
    for i in range(N):
        if visited[i]:
            continue
        tmp = dfs(G, visited, i, 1)
        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict


N, M = map(int, input().split())
parent = defaultdict(lambda: -1)


def union(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return
    parent[x] = y


def find(x):
    if parent[x] == -1:
        return x
    res = parent[x] = find(parent[x])
    return res

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


count = defaultdict(int)
for i in range(N):
    count[find(i)] += 1
print(max(count.values()))

Submission status: Runtime Error

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

N,M= (int(x) for x in input().rstrip('\n').split())
res = 1
aed = []
f = []
for _ in range(M):
  A,B = (int(x) for x in input().rstrip('\n').split())
  if A not in aed and B not in aed:
    f.append([A,B])
    aed.append(A)
    aed.append(B)
  elif A in aed and B not in aed:
    for x in f:
      if A in x:
        x.append(B)
        aed.append(B)
        break
  elif A not in aed and B in aed:
    for x in f:
      if B in x:
        x.append(A)
        aed.append(A)
        break
l = [len(x) for x in f]
print(max(l))

Submission status: Runtime Error

Solution code:
from collections import *
n,m=map(int,input().split())
d=[]
for i in range(m):
    l=list(map(int,input().split()))
    if(sorted(l) not in d):
        d.append(sorted(l))
dd=defaultdict(int)
for i in d:
    dd[i[0]]+=1
    dd[i[1]]+=1
k=max(dd.values())
print(k+1)

Submission status: Runtime Error

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

G = []
m = {}
for a, b in zip(A, B):
    if a not in m and b not in m:
        G.append({a, b})
        m[a] = len(G) - 1
        m[b] = len(G) - 1
    elif a in m:
        gid = m[a]
        G[gid].add(b)
        m[b] = gid
    elif b in m:
        gid = m[b]
        G[gid].add(a)
        m[a] = gid

if M == 0:
    print(1)
else:
    print(max(len(g) for g in G))

Submission status: Runtime Error

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

parent_dict = dict() #key:子 value:親

#接続追加
def add_connect(A,B):
    A_parent = get_parent(A)
    B_parent = get_parent(B)
    
    if A_parent != B_parent:
        parent_dict[B_parent] = A_parent

#接続有無判断
def judge_connection(A,B):
    A_parent = get_parent(A) #未更新状態でも、ここで更新される
    B_parent = get_parent(B)
    
    if A_parent != B_parent:
        return False
    else:
        return True

#親の取得
def get_parent(child):
    if child not in parent_dict: #初出なら自分自身を親として追加
        parent_dict[child] = child
    
    parent = parent_dict[child]
    
    if parent == child: 
        return parent
    else: #最上位の親なら上の等式が成り立つ。不成立ならさらに上位の親を辿る。
        parent_dict[child] = get_parent(parent) 
        return parent_dict[child]

##注意!!　全入力完了後にget_parentをしないと、正しい親が得られない
#ex 12 23 13 56 61 43→{1: 5, 2: 1, 3: 5, 5: 4, 6: 5, 4: 4}になる
for i in range(M):
    A,B = map(int, input().split())
    add_connect(A,B)

for i in range(1,N+1):
    get_parent(i)
  
#最も子が多い親を求めるために、親:子の辞書を作る
child_dict = dict() #key:親 value:子

for i in range(1,N+1):
    if parent_dict[i] not in child_dict:
        child_dict[parent_dict[i]] = set()
    child_dict[parent_dict[i]].add(i)


ans = 1
for parent in child_dict:
    if len(child_dict[parent]) > ans:
        ans = len(child_dict[parent])

print(ans)

Submission status: Runtime Error

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

Fmap=[]
a,b=map(int,input().split())
Fmap.append([a,b])

for i in range(m-1):
  a,b=map(int,input().split())
  for listF in Fmap:
    if a in listF:
      if b in listF:
        pass
      else:
        listF.append(b)
    if b in listF:
      if a in listF:
      	pass
      else:
        listF.append(a)

maxLenF=2

for i in Fmap:
  if len(i)>maxLenF:
    maxLenF=len(i)
print(maxLenF)

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
ex = [0 for i in range(n)]
fri = {}

for i in range(m):
    a, b = map(int, input().split())
    if ex[a-1] == 0 and ex[b-1] == 0:
        if a > b:
            a, b = b,a
        ex[a-1] = a
        ex[b-1] = a
        fri[a] = [a, b]
    elif ex[a-1] == 0:
        ex[a-1] = ex[b-1]
        fri[ex[b-1]].append(a)
    elif ex[b-1] == 0:
        ex[b-1] = ex[a-1]
        fri[ex[a-1]].append(b)
    elif ex[a-1] == ex[b-1]:
        continue
    else:
        shozoku = min(ex[a-1], ex[b-1])
        mu = max(ex[a-1], ex[b-1])
        fri[shozoku].extend(fri.pop(mu))

ans = 0
for key in fri:
    ans = max(ans, len(fri[key]))
print(ans)

Submission status: Runtime Error

Solution code:
N,M = map(int, input().split())
AB = [list(map(int, input().split())) for i in range(M)]
appear = [0] * (N+1) 

ans = 2
appear[AB[0][0]] = 1
appear[AB[0][1]] = 1

for i in range(1,M):
    # print(ans, AB[i][0],appear[AB[i][0]] ,AB[i][1], appear[AB[i][1]] )
    if appear[AB[i][0]] == 0 and appear[AB[i][1]] == 0:
        appear[AB[i][0]] = 1
        appear[AB[i][1]] = 1
    elif appear[AB[i][0]] == 0 and appear[AB[i][1]] == 1:
        ans += 1
        appear[AB[i][0]] = 1
    elif appear[AB[i][0]] == 1 and appear[AB[i][1]] == 0:
        ans += 1
        appear[AB[i][1]] = 1

print(ans)