Problem:


Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

The input is given from Standard Input in the following format:

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

7 4 4
1 2
2 3
2 5
6 7
3 5
4 5
3 4
6 7

Sample Output 3

1 1 2 1 2 2 2



Sample input:
4 3 1
1 2
2 3
3 4
2 3


Sample output:
1 2 2 1

Submission status: Runtime Error

Solution code:
import sys
import collections as c
sys.setrecursionlimit(10**6)

class UnionFind():
	def __init__(self, n):
		self.size = n
		self.root = [-1 for _ in range(n+1)]
		self.rnk = [0 for _ in range(n+1)]

	def findRoot(self, a):
		if self.root[a] < 0:
			return a
		else:
			return self.findRoot(self.root[a])

	def uniteTree(self, a, b):
		a = self.findRoot(a)
		b = self.findRoot(b)

		if a == b:
			return

		elif self.rnk[a] > self.rnk[b]:
			self.root[a] += self.root[b]
			self.root[b] = a

		elif self.rnk[b] > self.rnk[a]:
			self.root[b] += self.root[a]
			self.root[a] = b

		elif self.rnk[a] == self.rnk[b]:
			self.root[b] += self.rnk[a]
			self.root[a] = b
			self.rnk[b] += 1

	def judgeTree(self, a, b):
		return self.findRoot(a) == self.findRoot(b)

	def count(self, a):
		return self.rnk[self.findRoot(a)] * (-1)

N, K, L = map(int,input().split())
p = []
q = []
l = []
r = []

for _ in range(K):
	p_tmp, q_tmp = map(int ,input().split())
	p.append(p_tmp)
	q.append(q_tmp)

for _ in range(L):
	l_tmp, r_tmp = map(int, input().split())
	l.append(l_tmp)
	r.append(r_tmp)

road = UnionFind(N)
train = UnionFind(N)

for i in range(K):
	road.uniteTree(p[i], q[i])

for i in range(L):
	train.uniteTree(l[i], r[i])

ar = ["[-1,-1]"]

for i in range(1,N+1):
	a = road.findRoot(i)
	b = train.findRoot(i)
	ar.append(str([a,b]))

Car = c.Counter(ar)

for i in range(1,N+1):
	print(Car[ar[i]], end = " ")

Submission status: Runtime Error

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


class UnionFind():
	def __init__(self, n):
		self.size = n
		self.root = [-1 for _ in range(n+1)]
		self.rnk = [0 for _ in range(n+1)]

	def findRoot(self, a):
		if self.root[a] < 0:
			return a
		else:
			return self.findRoot(self.root[a])

	def uniteTree(self, a, b):
		a = self.findRoot(a)
		b = self.findRoot(b)

		if a == b:
			return

		elif self.rnk[a] > self.rnk[b]:
			self.root[a] += self.root[b]
			self.root[b] = a

		elif self.rnk[b] > self.rnk[a]:
			self.root[b] += self.root[a]
			self.root[a] = b

		elif self.rnk[a] == self.rnk[b]:
			self.root[b] += self.rnk[a]
			self.root[a] = b
			self.rnk[b] += 1

	def judgeTree(self, a, b):
		return self.findRoot(a) == self.findRoot(b)

	def count(self, a):
		return self.rnk[self.findRoot(a)] * (-1)

N, K, S = map(int, input().split())
P = []
Q = []
R = []
L = []

for _ in range(K):
	p_tmp, q_tmp = map(int, input().split())
	P.append(p_tmp)
	Q.append(q_tmp)

for _ in range(S):
	r_tmp, l_tmp = map(int, input().split())
	R.append(r_tmp)
	L.append(l_tmp)
	
road = UnionFind(N)
train = UnionFind(N)

for i in range(K):
	road.uniteTree(P[i], Q[i])

for i in range(S):
	train.uniteTree(R[i], L[i])

ans = [1 for _ in range(N)]

for i in range(1, N+1):
	for j in range(1, N+1):
		if i == j:
			continue
		else:
			if road.judgeTree(i,j) and train.judgeTree(i,j):
				ans[i-1] += 1

for i in ans:
	print(i, end = " ")

Submission status: Runtime Error

Solution code:
class UnionFind():
	def __init__(self, n):
		self.size = n
		self.root = [-1 for _ in range(n+1)]
		self.rnk = [0 for _ in range(n+1)]

	def findRoot(self, a):
		if self.root[a] < 0:
			return a
		else:
			return self.findRoot(self.root[a])

	def uniteTree(self, a, b):
		a = self.findRoot(a)
		b = self.findRoot(b)

		if a == b:
			return

		elif self.rnk[a] > self.rnk[b]:
			self.root[a] += self.root[b]
			self.root[b] = a

		elif self.rnk[b] > self.rnk[a]:
			self.root[b] += self.root[a]
			self.root[a] = b

		elif self.rnk[a] == self.rnk[b]:
			self.root[b] += self.rnk[a]
			self.root[a] = b
			self.rnk[b] += 1

	def judgeTree(self, a, b):
		return self.findRoot(a) == self.findRoot(b)

	def count(self, a):
		return self.rnk[self.findRoot(a)] * (-1)

N, K, S = map(int, input().split())
P = []
Q = []
R = []
L = []

for _ in range(K):
	p_tmp, q_tmp = map(int, input().split())
	P.append(p_tmp)
	Q.append(q_tmp)

for _ in range(S):
	r_tmp, l_tmp = map(int, input().split())
	R.append(r_tmp)
	L.append(l_tmp)
	
road = UnionFind(N)
train = UnionFind(N)

for i in range(K):
	road.uniteTree(P[i], Q[i])

for i in range(S):
	train.uniteTree(R[i], L[i])

ans = [1 for _ in range(N)]

for i in range(1, N+1):
	for j in range(1, N+1):
		if i == j:
			continue
		else:
			if road.judgeTree(i,j) and train.judgeTree(i,j):
				ans[i-1] += 1

for i in ans:
	print(i, end = " ")

Submission status: Runtime Error

Solution code:
class UF:
    def __init__(self, N):
        self.uf = [-1]*N
        self.n = N

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

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

    def union(self, x, y):
	x, y = self.find(x), self.find(y)
        if x==y: return
        if self.size(x) > self.size(y): x, y = y, x
        self.uf[y] += self.uf[x]
	self.uf[x] = y
        self.n -= 1

N, K, L = list(map(int, input().split()))
uf1, uf2 = UF(N), UF(N)
for _ in range(K):
    p, q = list(map(int, input().split()))
    uf1.union(p-1, q-1)

for _ in range(L):
    r, s = list(map(int, input().split()))
    uf2.union(r-1, s-1)

keys = [(uf1.find(x), uf2.find(x)) for x in range(N)]
count = {}
for key in keys:
    if key in count: count[key]+=1
    else: count[key]=1

print(*[count[key] for key in keys])

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)

class UF:
    def __init__(self, N):
        self.uf = [-1]*N

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

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

    def union(self, x, y):
        x, y = self.find(x), self.find(y)
        if self.size(x) > self.size(y): x, y = y, x
        self.uf[y] += self.uf[x]
        self.uf[x] = y

N, K, L = list(map(int, input().split()))
uf1, uf2 = UF(N), UF(N)
for _ in range(K):
    p, q = list(map(int, input().split()))
    uf1.union(p-1, q-1)

for _ in range(L):
    r, s = list(map(int, input().split()))
    if uf1.find(r-1)==uf1.find(s-1):
        uf2.union(r-1, s-1)

print(*[uf2.size(x) for x in range(N)])

Submission status: Runtime Error

Solution code:
class UF:
    def __init__(self, N):
        self.uf = [-1]*N

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

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

    def union(self, x, y):
        x, y = self.find(x), self.find(y)
        if self.size(x) > self.size(y): x, y = y, x
        self.uf[y] += self.uf[x]
        self.uf[x] = y

N, K, L = list(map(int, input().split()))
uf1, uf2 = UF(N), UF(N)
for _ in range(K):
    p, q = list(map(int, input().split()))
    uf1.union(p-1, q-1)

for _ in range(L):
    r, s = list(map(int, input().split()))
    if uf1.find(r-1)==uf1.find(s-1):
        uf2.union(r-1, s-1)

print(*[uf2.size(x) for x in range(N)])

Submission status: Runtime Error

Solution code:
class UF:
    def __init__(self, N):
        self.uf = [-1]*N

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

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

    def union(self, x, y):
	x, y = self.find(x), self.find(y)
	if self.size(x) > self.size(y): x, y = y, x
	self.uf[y] += self.uf[x]
	self.uf[x] = y

N, K, L = list(map(int, input().split()))
uf1, uf2 = UF(N), UF(N)
for _ in range(K):
    p, q = list(map(int, input().split()))
    uf1.union(p-1, q-1)

for _ in range(L):
    r, s = list(map(int, input().split()))
    if uf1.find(r-1)==uf1.find(s-1):
        uf2.union(r-1, s-1)

print(*[uf2.size(x) for x in range(N)])

Submission status: Runtime Error

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

N,K,L=map(int,input().split())

pq=[list(map(int,input().split())) for _ in range(K)]
rs=[list(map(int,input().split())) for _ in range(L)]

city_road=set()
city_train=set()
city_road_train=set()

city_roadgroup_dict={}
roadgroup_city_dict={}

city_traingroup_dict={}
traingroup_city_dict={}

for ch_pq in pq:
  for pq_i in range(2): 
    if not ch_pq[pq_i] in city_road:
      city_road.add(ch_pq[pq_i])
    
  if not ch_pq[0] in city_roadgroup_dict:
    if not ch_pq[1] in city_roadgroup_dict:
      city_roadgroup_dict[ch_pq[0]]=len(roadgroup_city_dict)
      city_roadgroup_dict[ch_pq[1]]=len(roadgroup_city_dict)
      roadgroup_city_dict[len(roadgroup_city_dict)]=set([ch_pq[0],ch_pq[1]])
    else:
      city_roadgroup_dict[ch_pq[0]]=city_roadgroup_dict[ch_pq[1]]
      roadgroup_city_dict[city_roadgroup_dict[ch_pq[1]]].add(ch_pq[0])
  elif not ch_pq[1] in city_roadgroup_dict:
      city_roadgroup_dict[ch_pq[1]]=city_roadgroup_dict[ch_pq[0]]
      roadgroup_city_dict[city_roadgroup_dict[ch_pq[0]]].add(ch_pq[1])

for ch_rs in rs:
  for rs_i in range(2): 
    if not ch_rs[rs_i] in city_road_train and ch_rs[rs_i] in city_road:
      city_road_train.add(ch_rs[rs_i])
  
  if not ch_rs[0] in city_traingroup_dict:
    if not ch_rs[1] in city_traingroup_dict:
      city_traingroup_dict[ch_rs[0]]=len(traingroup_city_dict)
      city_traingroup_dict[ch_rs[1]]=len(traingroup_city_dict)
      traingroup_city_dict[len(traingroup_city_dict)]=set([ch_rs[0],ch_rs[1]])
    else:
      city_traingroup_dict[ch_rs[0]]=city_traingroup_dict[ch_rs[1]]
      traingroup_city_dict[city_traingroup_dict[ch_rs[1]]].add(ch_rs[0])
  elif not ch_rs[1] in city_traingroup_dict:
      city_traingroup_dict[ch_rs[1]]=city_traingroup_dict[ch_rs[0]]
      traingroup_city_dict[city_traingroup_dict[ch_rs[0]]].add(ch_rs[1])
  
city_both_conn_num=['1']*N
for ch_city in list(city_road_train):
  group_n=city_traingroup_dict[ch_city]
  city_both_conn_num[ch_city-1]=str(len(roadgroup_city_dict[group_n] \
  & traingroup_city_dict[group_n]))


print(' '.join(city_both_conn_num))

Submission status: Runtime Error

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

N,K,L=map(int,input().split())

pq=[list(map(int,input().split())) for _ in range(K)]
rs=[list(map(int,input().split())) for _ in range(L)]

city_road=set()
city_train=set()
city_road_train=set()

city_roadgroup_dict={}
roadgroup_city_dict={}

city_traingroup_dict={}
traingroup_city_dict={}

for ch_pq in pq:
  for pq_i in range(2): 
    if not ch_pq[pq_i] in city_road:
      city_road.add(ch_pq[pq_i])
    
  if not ch_pq[0] in city_roadgroup_dict:
    if not ch_pq[1] in city_roadgroup_dict:
      city_roadgroup_dict[ch_pq[0]]=len(roadgroup_city_dict)
      city_roadgroup_dict[ch_pq[1]]=len(roadgroup_city_dict)
      roadgroup_city_dict[len(roadgroup_city_dict)]=set([ch_pq[0],ch_pq[1]])
    else:
      city_roadgroup_dict[ch_pq[0]]=city_roadgroup_dict[ch_pq[1]]
      roadgroup_city_dict[city_roadgroup_dict[ch_pq[1]]].add(ch_pq[0])
  elif not ch_pq[1] in city_roadgroup_dict:
      city_roadgroup_dict[ch_pq[1]]=city_roadgroup_dict[ch_pq[0]]
      roadgroup_city_dict[city_roadgroup_dict[ch_pq[0]]].add(ch_pq[1])

for ch_rs in rs:
  for rs_i in range(2): 
    if not ch_rs[rs_i] in city_road_train and ch_rs[rs_i] in city_road:
      city_road_train.add(ch_rs[rs_i])
  
  if not ch_rs[0] in city_traingroup_dict:
    if not ch_rs[1] in city_traingroup_dict:
      city_traingroup_dict[ch_rs[0]]=len(traingroup_city_dict)
      city_traingroup_dict[ch_rs[1]]=len(traingroup_city_dict)
      traingroup_city_dict[len(traingroup_city_dict)]=set([ch_rs[0],ch_rs[1]])
    else:
      city_traingroup_dict[ch_rs[0]]=city_traingroup_dict[ch_rs[1]]
      traingroup_city_dict[city_traingroup_dict[ch_rs[1]]].add(ch_rs[0])
  elif not ch_rs[1] in city_traingroup_dict:
      city_traingroup_dict[ch_rs[1]]=city_traingroup_dict[ch_rs[0]]
      traingroup_city_dict[city_traingroup_dict[ch_rs[0]]].add(ch_rs[1])
  
city_both_conn_num=['1']*N
for ch_city in list(city_road_train):
  group_n=city_traingroup_dict[ch_city]
  city_both_conn_num[ch_city-1]=str(len(roadgroup_city_dict[group_n] \
  & traingroup_city_dict[group_n]))


print(' '.join(city_both_conn_num))

Submission status: Runtime Error

Solution code:
def create_links(n, k):
  links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, readline().split())
    links[p - 1].append(q - 1)
    links[q - 1].append(p - 1)
  return links

def create_groups(n, links):
  groups = list(range(n))
  for i in range(n):
    if groups[i] != i:
      continue
    q = [i]
    while q:
      j = q.pop()
      for k in links[j]:
        if groups[k] != i:
          groups[k] = i
          q.append(k)

n, k, l = map(int, input().split())
road_links = create_links(n, k)
rail_links = create_links(n, l)
road_groups = create_groups(n, road_links)
rail_groups = create_groups(n, rail_links)
d = {}
for i in range(n):
  t = (road_groups[i], rail_groups[i])
  if t in d:
    d[t] += 1
  else:
    d[t] = 1
print(*[d[(road_groups[i], rail_groups[i])] for i in range(n)])

Submission status: Runtime Error

Solution code:
from sys import stdin

def main():
  def find(parent, i):
    t = parent[i]
    if t == -1:
      return i
    t = find(parent, t)
    parent[i] = t
    return t

  def unite(parent, i, j):
    i = find(parent, i)
    j = find(parent, j)
    if i == j:
      return
    parent[i] = j

  from builtins import int, map, range
  readline = stdin.readline()

  n, k, l = map(int, readline().split())

  roads = [-1] * n
  rails = [-1] * n

  for i in range(k):
    p, q = map(int, readline().split())
    unite(roads, p - 1, q - 1)

  for i in range(l):
    p, q = map(int, readline().split())
    unite(rails, p - 1, q - 1)

  d = {}
  for i in range(n):
    t = (find(roads, i), find(rails, i))
    if t in d:
      d[t] += 1
    else:
      d[t] = 1

  print(*[d[(find(roads, i), find(rails, i))] for i in range(n)])

main()

Submission status: Runtime Error

Solution code:
from collections import deque
from sys import stdin
def create_groups(n, links):
  from builtins import len, set
  groups = [-1 for _ in range(n)]
  group_number = 0
  d = deque()
  for i in range(n):
    if groups[i] == -1:
      group_member = []
      d.append(i)
      while len(d) != 0:
        j = d.popleft()
        groups[j] = group_number
        group_member.append(j)
        for k in links[j]:
          if groups[k] == -1:
            d.append(k)
      group_number += 1
  return groups
def read_links(n, k):
  from builtins import int, map
  readline = stdin.readline
  links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, readline().split())
    links[p - 1].append(q - 1)
    links[q - 1].append(p - 1)
  return links
def main():
  from builtins import len
  n, k, l = map(int, input().split())
  road_links = read_links(n, k)
  train_links = read_links(n, l)
  road_groups = create_groups(n, road_links)
  train_groups = create_groups(n, train_links)
  result = {}
  for i in range(n):
    t = (road_groups[i], train_groups[i])
    if t in result:
      result[t] += 1
    else:
      result[t] +=1
  print(*[result[(road_groups[i], train_groups[i])] for i in range(n)])
main()

Submission status: Runtime Error

Solution code:
mport sys
input = sys.stdin.readline
 
def Find(x, par):
  if par[x] < 0:
    return x
  else:
    # 経路圧縮
    par[x] = Find(par[x], par)
    return par[x]

def Unite(x, y, par, rank):
  x = Find(x, par)
  y = Find(y, par)
  
  if x != y:
    # rankの低い方を高い方につなげる
    if rank[x] < rank[y]:
      par[y] += par[x]
      par[x] = y
    else:
      par[x] += par[y]
      par[y] = x
      if rank[x] == rank[y]:
        rank[x] += 1
    
def Same(x, y, par):
  return Find(x, par) == Find(y, par)
 
def Size(x, par):
  return -par[Find(x)]
 
n, k, l = map(int, input().split())
rpar = [-1]* n
tpar = [-1]* n
rrank = [0]*n
trank = [0]*n
 
for i in range(k):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, rpar, rrank) 

for i_ in range(l):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, tpar, trank)

d = {}
IDs = [0]*n
for j in range(n):
  ID = Find(j, rpar)+(Find(j, tpar)+1)*10**8
  IDs[j] = ID
  if ID in d:
    d[ID] += 1
  else:
    d[ID] = 1

ans = ''
for j_ in range(n):
  if j_ != 0:
    ans += ' '
  ans += str(d[IDs[j_]])
print(ans)

Submission status: Runtime Error

Solution code:
def find_root(edges, root, group, before, now):
    group.append(now)
    children = edges[now]
    for child in children:
        if child != before and child not in group:
            root, group = find_root(edges, root, group, now, child)
    return root, group
    
if __name__ == '__main__':
    N, K, L = map(int, input().split())
    roads = [[] for _ in range(N)]
    rails = [[] for _ in range(N)]
    road_roots = [None]*N
    rail_roots = [None]*N
    answer = [1]*N
        
    for i in range(K):
        p, q = map(int, input().split())
        p -= 1
        q -= 1
        roads[p].append(q)
        roads[q].append(p)
    
    for i in range(L):
        r, s = map(int, input().split())
        r -= 1
        s -= 1
        rails[r].append(s)
        rails[s].append(r)
    
    for i, r in enumerate(road_roots):
        if r is None:
            root, group = find_root(roads, i, [], -1, i)
            for g in group:
                road_roots[g] = root

    for i, r in enumerate(rail_roots):
        if r is None:
            root, group = find_root(rails, i, [], -1, i)
            for g in group:
                rail_roots[g] = root
    railroads=[[rail, road] for rail, road in zip(road_roots, rail_roots)]

    for n in range(N):
        for d in range(1, N-n):
            if railroads[n] == railroads[n+d]:
                answer[n] += 1 
                answer[n+d] += 1
    print(' '.join(list(map(str, answer))))

Submission status: Runtime Error

Solution code:
if __name__ == '__main__':
    N, K, L = map(int, input().split())
    PQ = [None]*K
    RS = [None]*L
    roads = [set() for _ in range(N)]
    rails = [set() for _ in range(N)]
    answer = [None]*N
        
    for i in range(K):
        PQ[i] = list(map(int, input().split()))
    #PQ = sorted(PQ, key=min)
    
    
    for i in range(K):
        if not roads[PQ[i][1] - 1]:
            roads[PQ[i][0] - 1].add(PQ[i][0] - 1)
            roads[PQ[i][0] - 1].add(PQ[i][1] - 1)
            roads[PQ[i][1] - 1] = roads[PQ[i][0] - 1]
        else:
            roads[PQ[i][1] - 1].add(PQ[i][0] - 1)
            roads[PQ[i][1] - 1].add(PQ[i][1] - 1)
            roads[PQ[i][0] - 1] = roads[PQ[i][1] - 1]

    for i in range(L):
        RS[i] = list(map(int, input().split()))
    #RS = sorted(RS, key=min)
    
    for i in range(L):
        if not rails[PQ[i][1] - 1]:
            rails[RS[i][0] - 1].add(RS[i][0] - 1)
            rails[RS[i][0] - 1].add(RS[i][1] - 1)
            rails[RS[i][1] - 1] = rails[RS[i][0] - 1]
        else:
            rails[RS[i][1] - 1].add(RS[i][0] - 1)
            rails[RS[i][1] - 1].add(RS[i][1] - 1)
            rails[RS[i][0] - 1] = rails[RS[i][1] - 1]

    for n in range(N):
        roads[n].add(n)
        rails[n].add(n)
        answer[n]= len(roads[n] & rails[n])
    
    
            
    print(' '.join(map(str, answer)))

Submission status: Runtime Error

Solution code:
from collections import*
n,k,l=map(int,input().split());d=[-1]*n;t=[-1]*n;M=lambda:map(int,input().split())
def f(l,x):return x if l[x]<0else f(l,l[x])
def u(l,x,y):
  if f(l,x)!=f(l,y):l[f(l,y)]=f(l,x)
for _ in range(k):a,b=M();u(d,a-1,b-1)
for _ in range(l):a,b=M();u(t,a-1,b-1)
p=[(f(d,i),f(t,i))for i in range(n)];c=Counter(p);print(*[c[p[i]]for i in range(n)])

Submission status: Runtime Error

Solution code:
from collections import*
n,k,l=map(int,input().split());d=[-1]*n;t=[-1]*n
def f(l,x):
  if l[x]<0:return x
  else:l[x]=f(l,l[x]);return l[x]
def u(l,x,y):l[f(l,y)]=f(l,x)
for _ in range(k):a,b=map(int,input().split());u(d,a-1,b-1)
for _ in range(l):a,b=map(int,input().split());u(t,a-1,b-1)
p=[(f(d,i),f(t,i))for i in range(n)];c=Counter(p);print(*[c[p[i]]for i in range(n)])

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n, k, l = [ int(v) for v in input().split() ]
road_parent = [ i for i in range(n) ]
rail_parent = [ i for i in range(n) ]

def parent(x,a,inlist):
    if inlist[x] == x:
        return x, a
    else:
        return parent(inlist[x],a+1,inlist)

def union(z,inlist):
    x, y = z[0], z[1]
    inlist[x], rank_x = parent(x,0,inlist)
    inlist[y], rank_y = parent(y,0,inlist)
    if inlist[x] != inlist[y]:
        if rank_x > rank_y:
            inlist[inlist[y]] = inlist[x]
        else:
            inlist[inlist[x]] = inlist[y]
    return

for i in range(n):
    road = [ int(v)-1 for v in input().split() ]
    union(road,road_parent)

for i in rail_list:
    rail = [ int(v)-1 for v in input().split() ]
    union(rail,rail_parent)

road_parent = [ parent(i,0,road_parent)[0] for i in range(n) ]
rail_parent = [ parent(i,0,rail_parent)[0] for i in range(n) ]
print(road_parent)
print(rail_parent)

Submission status: Runtime Error

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

class UnionFind:
    def __init__(self, n):
        self.data = [0] * N
        self.dd = [{i} for i in range(N)]
        for i in range(N):
            self.data[i] = i
            
    def get_root(self, x):
        r = self.data[x]
        if r == x:
            return r
        p = self.get_root(r)
        self.data[x] = p
        
        self.dd[x].add(p)
        self.dd[p].add(x)
        
        return p
    
    def unite(self, x, y):
        rx = self.get_root(x)
        ry = self.get_root(y)
        
        if rx != ry:
            self.data[rx] = ry

            self.dd[x].add(y)
            self.dd[y].add(x)
            
    def same(self, x, y):
        return self.get_root(x) == self.get_root(y)

N, K, L = map(int, input().split())
LA = [[int(v) - 1 for v in input().split()] for _ in range(K)]
LB = [[int(v) - 1 for v in input().split()] for _ in range(K)]

u1 = UnionFind(N)
for x, y in LA:
    u1.unite(x, y)
    
u2 = UnionFind(N)
for x, y in LB:
    u2.unite(x, y)
    
result = [0] * N
for i in range(N):
    a = u1.get_root(i)
    b = u2.get_root(i)
    
    result[i] = len(u1.dd[a] & u2.dd[b])
    
print(" ".join(map(str, result)))

Submission status: Runtime Error

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

class UnionFind:
    def __init__(self, n):
        self.data = [0] * N
        self.dd = [{i} for i in range(N)]
        for i in range(N):
            self.data[i] = i
            
    def get_root(self, x):
        r = self.data[x]
        if r == x:
            return r
        p = self.get_root(r)
        self.data[x] = p
        
        return p
    
    def unite(self, x, y):
        rx = self.get_root(x)
        ry = self.get_root(y)
        
        if rx != ry:
            self.data[rx] = ry

            self.dd[ry] = self.dd[x] | self.dd[ry]
            self.dd[ry] = self.dd[y] | self.dd[ry]
            self.dd[ry] = self.dd[rx] | self.dd[ry]
            
    def same(self, x, y):
        return self.get_root(x) == self.get_root(y)

N, K, L = map(int, input().split())
LA = [[int(v) - 1 for v in input().split()] for _ in range(K)]
LB = [[int(v) - 1 for v in input().split()] for _ in range(K)]

u1 = UnionFind(N)
for x, y in LA:
    u1.unite(x, y)
    
u2 = UnionFind(N)
for x, y in LB:
    u2.unite(x, y)
    
result = [0] * N
for i in range(N):
    a = u1.get_root(i)
    b = u2.get_root(i)
    
    result[i] = len(u1.dd[a] & u2.dd[b])
    
print(" ".join(map(str, result)))

Submission status: Runtime Error

Solution code:
input = sys.stdin.readline
n,k,l=map(int,input().split())

parD,parT=[-1]*n,[-1]*n
def findD(x):
  if parD[x]<0:
    return x
  else:
    parD[x]=findD(parD[x])
    return parD[x]
def uniteD(x,y):
  x=findD(x)
  y=findD(y)
  if x==y:
    return False
  else:
    if parD[x]>parD[y]:
      x,y=y,x
    parD[x]+=parD[y]
    parD[y]=x
    return True
def sameD(x,y):
  return findD(x)==findD(y)
def sizeD(x):
  return -parD[findD(x)]
def findT(x):
  if parT[x]<0:
    return x
  else:
    parT[x]=findT(parT[x])
    return parT[x]
def uniteT(x,y):
  x=findT(x)
  y=findT(y)
  if x==y:
    return False
  else:
    if parT[x]>parT[y]:
      x,y=y,x
    parT[x]+=parT[y]
    parT[y]=x
    return True
def sameT(x,y):
  return findT(x)==findT(y)
def sizeD(x):
  return -parT[findT(x)]


for i in range(k):
  p,q=map(int,input().split())
  uniteD(p-1,q-1)
for i in range(l):
  r,s=map(int,input().split())
  uniteT(r-1,s-1)
for i in range(n):
  findD(i)
  findT(i)
C=[]
for i in range(n):
  if parD[i]<0:
    parD[i]=i
  if parT[i]<0:
    parT[i]=i
Ans=[]
for i in range(n):
  Ans.append((parD[i],parT[i]))
ANS=collections.Counter(Ans)
for i in range(n):
  print(ANS[Ans[i]])

Submission status: Runtime Error

Solution code:
import copy

class UnionFind:
	def __init__(self, N):
		self._parent = [i for i in range(N)]
		self._rank = [1 for i in range(N)]

	def find(self, x):
		if self._parent[x] == x:
			return x
		else:
			return self.find(self._parent[x])

	def unite(self, a, b):
		ta = self.find(a)
		tb = self.find(b)
		if(ta == tb):
			return
		
		if self._rank[ta] < self._rank[tb]:
			self._parent[ta] = tb # make b as a parent of a
		else:
			self._parent[tb] = ta # make a as a parent of b
			if(ta == tb) rank[ta] += 1
			
	def check(self, a, b):
		return self.find(a) == self.find(b)
		
if __name__ == '__main__':
	N,K,L = map(int, input().split())
	ans = [1 for _ in range(N+1)]
	uf = UnionFind(N+1)
	for _ in range(K):
		p,q = map(int, input().split())
		uf.unite(p,q)
	for _ in range(L):
		s,r = map(int, input().split())
		if uf.check(s,r):
			ans[s] += 1
			ans[r] += 1
	print(*ans[1::])

Submission status: Runtime Error

Solution code:
from collections import defaultdict

def dfs(i, V, E, num):
    V[i] = num
    for j in E[i]:
        if V[j] > 0:
            continue
        V = dfs(j, V, E, num)
    return V

n, k, l = map(int, input().split())
Er = defaultdict(list)
for i in range(k):
    p, q = map(int, input().split())
    Er[p].append(q)
    Er[q].append(p)
Et = defaultdict(list)
for i in range(l):
    r, s = map(int, input().split())
    Et[r].append(s)
    Et[s].append(r)

Vr_group = [None]
Vr = [0 for _ in range(n + 1)]
j = 1
for i in range(1, n + 1):
    if Vr[i] > 0:
        continue
    Vr = dfs(i, Vr, Er, j)
    Vr_group.append({t for t in range(1, n + 1) if Vr[t] == j})
    j += 1

Vt_group = [None]
Vt = [0 for _ in range(n + 1)]
j = 1
for i in range(1, n + 1):
    if Vt[i] > 0:
        continue
    Vt = dfs(i, Vt, Et, j)
    Vt_group.append({t for t in range(1, n + 1) if Vt[t] == j})
    j += 1

ans = []
for i in range(1, n + 1):
    ans.append(len(Vr_group[Vr[i]] & Vt_group[Vt[i]]))
print(' '.join([str(x) for x in ans]))

Submission status: Runtime Error

Solution code:
from collections import Counter

N,K,L = map(int, input().split())
pq_list = []
for _ in range(K):
    pq_list.append(list(map(int, input().split())))

rs_list = []
for _ in range(L):
    rs_list.append(list(map(int, input().split())))

class UnionFind():
    def __init__(self):
        self.roots = {}
        self.ranks = {}

    def connect(self,x,y):
        root_x = self.pick_root(x)
        root_y = self.pick_root(y)
        
        roots[x] = root_x
        roots[y] = root_y
        
        if not root_x == root_y:
            if self.ranks[root_x] >= self.ranks[root_y]:
                # 短い方の根を長い方の根にする
                # 等しいときはxにくっつける
                self.roots[y] = root_x
            else:
                self.roots[x] = root_y

            if self.ranks[root_x]==self.ranks[root_y]:
                # 等しいときxにくっつけると、xのランクが1増える
                self.ranks[x] += 1

    def pick_root(self,k):
        if not k in self.roots:
            self.roots[k] = k
            self.ranks[k] = 1
            return k

        k_root = self.roots[k]
        if k_root == k:
            return k
        else:
            # 経路圧縮（のつもり）
            # pick_rootで毎回見に行くのが無駄にも思えるが、いつ根ノードがくっつくかわからないので必要な気がしている
#             self.roots[k] = self.pick_root(self.roots[k_root])
#             return self.roots[k]
            return self.pick_root(k_root)

UF_pq = UnionFind()
for p,q in pq_list:
    UF_pq.connect(p, q)

UF_rs = UnionFind()
for r,s in rs_list:
    UF_rs.connect(r, s)

root_tuples = []
for i in range(1,N+1):
    if not i in UF_pq.roots:
        root_tuples.append((None,None))
        continue
    if not i in UF_rs.roots:
        root_tuples.append((None,None))
        continue
    pq_root = UF_pq.roots[i]
    rs_root = UF_rs.roots[i]
    root_tuples.append((pq_root,rs_root))

counter = Counter(root_tuples)
counter[(None,None)] = 1

kotae_list = []
for i in range(N):
    kotae_list.append(counter[root_tuples[i]])

print(" ".join(map(str,kotae_list)))

Submission status: Runtime Error

Solution code:
class UnionFind:
    def __init__(self, size: int):
        self.__size = size
        self.__root = [-1] * size

    def root(self, x: int)->int:
        if self.__root[x] < 0:
            return x
        self.__root[x] = self.root(self.__root[x])
        return self.__root[x]

    def size(self, x: int)->int:
        root = self.root(x)
        return self.__root[root]

    def same(self, x: int, y: int)->bool:
        return self.root(x) == self.root(y)

    def unite(self, x: int, y: int):
        rx, ry = self.root(x), self.root(y)

        if rx == ry:
            return

        if ry < rx:
            rx, ry = ry, rx

        self.__root[rx] += self.__root[ry]
        self.__root[ry] = rx


def connectivity(N: int, K: int, L: int, roads: list, rails: list)->list:
    road_uf, rail_uf = UnionFind(N), UnionFind(N)

    for p, q in roads:
        road_uf.unite(p-1, q-1)

    for r, s in rails:
        rail_uf.unite(r-1, s-1)

    freq = {}
    for i in range(N):
        p = (road_uf.root(i), rail_uf.root(i))
        freq.setdefault(p, 0)
        freq[p] += 1

    return [freq[(road_uf.root(i), rail_uf.root(i))] for i in range(N)]


if __name__ == "__main__":
    K = 0
    L = 0
    N, K, L = map(int, input().split())
    roads = [tuple(int(s) for s in input().split()) for _ in range(K)]
    rails = [tuple(int(s) for s in input().split()) for _ in range(K)]
    ans = connectivity(N, K, L, roads, rails)
    print(' '.join(map(str, ans)))