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: Wrong Answer

Solution code:
class UnionFind():
  def __init__(self, n):
    self.parent = [x for x in range(n+1)]
    self.rank = [0]*(n+1)
    
  def marge(self, a, b):
    x=self.find_root(a)
    y=self.find_root(b)
    
    if self.rank[x] < self.rank[y]:
      self.parent[x] = y
    else:
      self.parest[y] = x
      
      if self.rank[x] == self.rank[y]:
        self.rank[x] += 1
      
  def find_root(self, a):
    if self.parent[a] == a:
      return a
    else:
      self.parent[a] = self.find_root(self.parent[a])
      return self.parent[a]
  
def __main__():
  n,k,l = map(int,input().split())
  uf1 = UnionFind(n)
  uf2 = UnionFind(n)
  for i in range(k):
    p,q = map(int,input().split())
    uf1.marge(p,q)
  for i in range(l):
    r,s = map(int, input().split())
    uf2.merge(r,s)
  ans={}
  key_list=[]
  for i in range(n):
    key = str(uf1.parent[i]) + '_' + str(uf2.parent[i])
    key_list.append(key)
  for i in range(n):
    if key_list[i] in ans.Keys():
      ans[key_list[i]] += 1
    else:
      ans[key_list[i]] = 1
  print(ans[i] for i in key_list)

Submission status: Wrong Answer

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

class UnionFind(object):
    def __init__(self, N):
        self.parent = [-1] * N

    def root(self, A):
        if self.parent[A-1] < 0:
            return A
        self.parent[A-1] = self.root(self.parent[A-1])
        return self.parent[A-1]

    def size(self, A):
        if self.parent[A-1] < 0:
            return -1 * self.parent[A-1]
        return -1 * self.parent[self.root(A)-1]

    def connect(self, A, B):
        A = self.root(A)
        B = self.root(B)
        if A == B:
            return False
        
        if self.size(A) < self.size(B):
            A, B = B, A
        
        self.parent[A-1] += self.parent[B-1]
        self.parent[B-1] = A
        return True
        
uni1 = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    if uni1.root(p) != uni1.root(q):
        uni1.connect(p,q)

uni2 = UnionFind(N)
for _ in range(L):
    r, s = map(int, input().split())
    if uni2.root(r) != uni2.root(s):
        uni2.connect(r,s)

# print (uni1.parent)
# print (uni2.parent)

# for i in range(1, N+1):
#     ans = 0
#     for j in range(1, N+1):
#         # print (uni1.root(i), uni1.root(j), uni2.root(i), uni2.root(j))
#         if uni1.root(i) == uni1.root(j) and uni2.root(i) == uni2.root(j):
#             ans += 1
#     print (ans, end = ' ')
print ()

# print (uni1.parent)
# print (uni2.parent)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import Counter
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

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

PQ = [[int(x) for x in input().split()] for _ in range(K)]
RS = [[int(x) for x in input().split()] for _ in range(L)]

P,Q = zip(*PQ)
R,S = zip(*RS)

g1 = csr_matrix(([1]*K,(P,Q)),(N+1,N+1))
g2 = csr_matrix(([1]*L,(R,S)),(N+1,N+1))

_,comp1 = connected_components(g1,directed = False,return_labels = True)
_,comp2 = connected_components(g2,directed = False,return_labels = True)

comp_pair = comp1 * (N+1) + comp2
c = Counter(comp_pair)

answer = [c[comp_pair[i]] for i in range(1,N+1)]
print(*answer)

Submission status: Wrong Answer

Solution code:
import copy

class UnionFind:
	def __init__(self, N):
		self._parent = [i for i in range(N)]
		self._rank = [0 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: Wrong Answer

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: Wrong Answer

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 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
			
		self._rank[ta] = max(self._rank[ta], self._rank[tb])
			
	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: Wrong Answer

Solution code:
class UF():
  def __init__(self, N):
    self._parent=[n for n in range(0, N)]
    self._size=[1] * N

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

  def unite(self, x, y):
    gx=self.find_root(x)
    gy=self.find_root(y)
    if gx==gy:return

    if self._size[gx]<self._size[gy]:
      self._parent[gx]=gy
      self._size[gy]+=self._size[gx]
    else:
      self._parent[gy]=gx
      self._size[gx]+=self._size[gy]

  def size(self, x):
    return self._size[self.find_root(x)]

  def samegroup(self, x, y):
    return self.find_root(x)==self.find_root(y)

  def groupnum(self):
    N=len(self._parent)
    ans=0
    for i in range(N):
      if self.find_root(i)==i:
        ans+=1
    return ans

from collections import defaultdict
n,k,l=map(int,input().split())
UF1=UF(n)
for i in range(k):
  p,q=map(int,input().split())
  UF1.unite(p-1,q-1)
UF2=UF(n)
for i in range(l):
  r,s=map(int,input().split())
  UF2.unite(r-1,s-1)
d=defaultdict(int)
for i in range(n):
  d[UF1._parent[i],UF2._parent[i]]+=1
ans=[]
for i in range(n):
  ans.append(str(d[UF1._parent[i],UF2._parent[i]]))
print(' '.join(ans))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as ddict
def find(ps,x):
    if ps[x]<0:
        return x
    else:
        ps[x]=find(ps,ps[x])
        return ps[x]
def unite(ps,x,y):
    x=find(ps,x)
    y=find(ps,y)
    if x==y:
        return False
    if ps[x]>ps[y]:
        x,y = y,x
    ps[x] += ps[y]
    ps[y] = x
    return True
def same(ps,x,y):
    return find(ps,x)==find(ps,y)
n,k,l = map(int,input().split())
tg = [-1]*(n+1)
rg = [-1]*(n+1)
for _ in range(k):
  p,q = map(int, input().split())
  unite(rg,p,q)
for _ in range(l):
  p,q = map(int, input().split())
  unite(tg,p,q)
td = ddict(list)
for x in range(1,n+1):
  if tg[x] < 0:
    td[x].append(x)
  else:
    td[tg[x]].append(x)
ans = [1]*(n+1)
for w in td.values():
  for i in w:
    for j in w:
      if i>=j:
        continue
      if same(rg,i,j):
        ans[i] += 1
        ans[j] += 1
print(" ".join(map(str,ans[1:])))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as ddict
def find(ps,x):
    if ps[x]<0:
        return x
    else:
        ps[x]=find(ps,ps[x])
        return ps[x]
def unite(ps,x,y):
    x=find(ps,x)
    y=find(ps,y)
    if x==y:
        return False
    if ps[x]>ps[y]:
        x,y = y,x
    ps[x] += ps[y]
    ps[y] = x
    return True
def same(ps,x,y):
    return find(ps,x)==find(ps,y)
n,k,l = map(int,input().split())
tg = [-1]*(n+1)
rg = [-1]*(n+1)
for _ in range(k):
  p,q = map(int, input().split())
  unite(rg,p,q)
for _ in range(l):
  p,q = map(int, input().split())
  unite(tg,p,q)
td = ddict(list)
for x in range(1,n+1):
  if tg[x] < 0:
    td[x].append(x)
  else:
    td[tg[x]].append(x)
ans = [1]*(n+1)
for w in td.values():
  for i in w:
    for j in w:
      if i>=j:
        continue
      if same(rg,i,j):
        ans[i] += 1
        ans[j] += 1
print(" ".join(map(str,ans[1:])))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
D - 連結 / Connectivity
https://atcoder.jp/contests/abc049/tasks/arc065_b

"""
import sys


class DisjointSet:
    def __init__(self, n):
        self.p = list(range(n))

    def root(self, i):
        if self.p[i] == i:
            return i
        else:
            self.p[i] = self.root(self.p[i])
            return self.p[i]

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

    def unite(self, i, j):
        i = self.root(i)
        j = self.root(j)
        if j >= i:
            self.p[j] = i
        else:
            self.p[i] = j


from collections import Counter

def solve(N, K, L, PQ, RS):
    r_d = DisjointSet(N+1)
    for p, q in PQ:
        r_d.unite(p, q)
    t_d = DisjointSet(N+1)
    for r, s in RS:
        t_d.unite(r, s)

    connectivity = Counter()
    for i in range(1, N+1):
        connectivity[(r_d.p[i], t_d.p[i])] += 1
    return [connectivity[(r_d.p[i], t_d.p[i])] for i in range(1, N + 1)]


def main(args):
    N, K, L = map(int, input().split())
    PQ = [[int(i) for i in input().split()] for _ in range(K)]
    RS = [[int(i) for i in input().split()] for _ in range(L)]
    ans = solve(N, K, L, PQ, RS)
    print(*ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
D - 連結 / Connectivity
https://atcoder.jp/contests/abc049/tasks/arc065_b

"""
import sys


class DisjointSet(object):
    def __init__(self, n):
        self.rank = [0] * n
        self.p = list(range(n))
        self.size = [1] * n

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

    def unite(self, x, y):
        a = self.findSet(x)
        b = self.findSet(y)
        if a > b:
            a, b = b, a
        self.link(a, b)

    def link(self, x, y):
        if self.rank[x] > self.rank[y]:
            self.size[self.p[x]] += self.size[self.p[y]]
            self.p[y] = self.findSet(x)
        else:
            self.size[self.p[y]] += self.size[self.p[x]]
            self.p[x] = self.findSet(y)
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

    def findSet(self, x):
        if x != self.p[x]:
            self.p[x] = self.findSet(self.p[x])
        return self.p[x]


from collections import Counter

def solve(N, K, L, PQ, RS):
    r_d = DisjointSet(N+1)
    for p, q in PQ:
        r_d.unite(p, q)
    t_d = DisjointSet(N+1)
    for r, s in RS:
        t_d.unite(r, s)

    connectivity = Counter()
    for i in range(1, N+1):
        connectivity[(r_d.p[i], t_d.p[i])] += 1
    return [connectivity[(r_d.p[i], t_d.p[i])] for i in range(1, N + 1)]


def main(args):
    N, K, L = map(int, input().split())
    PQ = [[int(i) for i in input().split()] for _ in range(K)]
    RS = [[int(i) for i in input().split()] for _ in range(L)]
    ans = solve(N, K, L, PQ, RS)
    print(*ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
D - 連結 / Connectivity
https://atcoder.jp/contests/abc049/tasks/arc065_b

"""
import sys


class DisjointSet(object):
    def __init__(self, n):
        self.rank = [0] * n
        self.p = list(range(n))
        self.size = [1] * n

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

    def unite(self, x, y):
        self.link(self.findSet(x), self.findSet(y))

    def link(self, x, y):
        if self.rank[x] > self.rank[y]:
            self.size[self.p[x]] += self.size[self.p[y]]
            self.p[y] = self.findSet(x)
        else:
            self.size[self.p[y]] += self.size[self.p[x]]
            self.p[x] = self.findSet(y)
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

    def findSet(self, x):
        if x != self.p[x]:
            self.p[x] = self.findSet(self.p[x])
        return self.p[x]


from collections import Counter

def solve(N, K, L, PQ, RS):
    r_d = DisjointSet(N+1)
    for p, q in PQ:
        r_d.unite(p, q)
    t_d = DisjointSet(N+1)
    for r, s in RS:
        t_d.unite(r, s)

    connectivity = Counter()
    for i in range(1, N+1):
        connectivity[(r_d.p[i], t_d.p[i])] += 1
    return [connectivity[(r_d.p[i], t_d.p[i])] for i in range(1, N + 1)]


def main(args):
    N, K, L = map(int, input().split())
    PQ = [[int(i) for i in input().split()] for _ in range(K)]
    RS = [[int(i) for i in input().split()] for _ in range(L)]
    ans = solve(N, K, L, PQ, RS)
    print(*ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
path = []
rail = []
for i in range(0, N):
	path.append(-1)
	rail.append(-1)
pathindex = 0
for i in range(0, K):
	p, q = map(int, input().split())
	if path[p-1] == -1 and path[q-1] == -1:
		path[p-1] = pathindex
		path[q-1] = pathindex
		pathindex += 1
	elif path[p-1] == -1:
		path[p-1] = path[q-1]
	elif path[q-1] == -1:
		path[q-1] = path[p-1]
railindex = 0
for i in range(0, L):
	p, q = map(int, input().split())
	if rail[p-1] == -1 and rail[q-1] == -1:
		rail[p-1] = railindex
		rail[q-1] = railindex
		railindex += 1
	elif rail[p-1] == -1:
		rail[p-1] = rail[q-1]
	elif rail[q-1] == -1:
		rail[q-1] = rail[p-1]
pathlist = []
for i in range(0, pathindex):
	pathlist.append([])
for i in range(0, N):
	if path[i] != -1:
		pathlist[path[i]].append(i)
raillist = []
for i in range(0, railindex):
	raillist.append([])
for i in range(0, N):
	if rail[i] != -1:
		raillist[rail[i]].append(i)
anslist = []
for i in range(0, N):
	if path[i] == -1 or rail[i] == -1:
		anslist.append(1)
	else:
		anslist.append(len(list(set(pathlist[path[i]]) & set(raillist[rail[i]]))))
ans = str(anslist[0])
for i in range(1, N):
	ans = ans + ' ' + str(anslist[i])
print(ans)

Submission status: Wrong Answer

Solution code:
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = s_inpl()   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = inpl()	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]

import math
import copy
from collections import defaultdict
from collections import Counter
from collections import deque
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
from bisect import bisect_left, bisect_right
# import numpy as np

def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W

# 四方向: 右, 下, 左, 上
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]

def i_inpl(): return int(input())
def s_inpl(): return map(int,input().split())
def l_inpl(): return list(map(int, input().split()))
INF = float("inf")

############
############
############

class UnionFind:
    
    def __init__(self, N):
        # 初期は全てが根
        self.parent = [ i for i in range(N)]
        self.rank = [0] * N

    # データxが属する木の根を求める
    def root_find(self, x):
        if self.parent[x] == x:
            return x
        else:
            return self.root_find(self.parent[x])

    # xとyの属する集合を合併
    def unite(self, x, y):
        x_root = self.root_find(x)
        y_root = self.root_find(y)

        if x_root == y_root:
            return 

        if self.rank[x_root] < self.rank[y_root]:
            self.parent[x_root] = y_root
        else:
            self.parent[y_root] = x_root
            if self.rank[x_root] == self.rank[y_root]:
                self.rank[x_root] += 1
    
    # xとyが属する集合が一緒かどうか
    def same(self, x, y):
        return self.root_find(x) == self.root_find(y)            

N, K, L = l_inpl()
k_uf = UnionFind(N)
l_uf = UnionFind(N)

for _ in range(K):
    p, q = l_inpl()
    p, q = p-1, q-1
    k_uf.unite(p, q)

for _ in range(L):
    r, s = l_inpl()
    r, s = r-1, s-1
    l_uf.unite(r, s)

d = []
for i in range(N):
    d.append([k_uf.parent[i], l_uf.parent[i]])

anss = []
for i in range(N):
    anss.append(str(d.count([k_uf.parent[i], l_uf.parent[i]])))

print(" ".join(anss))

Submission status: Wrong Answer

Solution code:
import collections
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
 
    def root(self, i):
        if self.parent[i] == i:
            return i
        else:
            self.parent[i] = self.root(self.parent[i])
            return self.parent[i]
    
    def find(self, x, y):
        return self.root(x) == self.root(y)
 
    def union(self, i, j):
        i = self.root(i)
        j = self.root(j)
        if j >= i:
            self.parent[j] = i
        else:
            self.parent[i] = j
N, K, L = map(int, input().split())
road = UnionFind(N)
train = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    road.union(p-1, q-1)
for _ in range(L):
    r, s = map(int, input().split())
    train.union(r-1, s-1)
lst = []
for i in range(N):
    lst.append((road.parent[i], train.parent[i]))
c = collections.Counter(lst)
ans = []
for i in range(N):
    ans.append(c[lst[i]])
print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import Counter
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

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

PQ = [[int(x) for x in input().split()] for _ in range(K)]
RS = [[int(x) for x in input().split()] for _ in range(L)]

P,Q = zip(*PQ)
R,S = zip(*RS)

g1 = csr_matrix(([1]*K,(P,Q)),(N+1,N+1))
g2 = csr_matrix(([1]*L,(R,S)),(N+1,N+1))

_,comp1 = connected_components(g1,directed = False,return_labels = True)
_,comp2 = connected_components(g2,directed = False,return_labels = True)

comp_pair = comp1 * (N+1) + comp2
c = Counter(comp_pair)

answer = [str(c[comp_pair[i]]) for i in range(1,N+1)]
print(' '.join(answer))

Submission status: Wrong Answer

Solution code:
# UnionFind
class UnionFind(object):
    # 親を表す配列 木はこの配列で表現する
    par = []
    rank = []

    def __init__(self, arg):
        super(UnionFind, self).__init__()
        self.par = [i for i in range(arg)]
        self.rank = [0 for i in range(arg)]

    # 木の根を求める
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # xとyの属する集合を結合
    def unite(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)

        if root_x == root_y:
            return

        if self.rank[root_x] > self.rank[root_y]:
            self.par[root_y] = root_x
        else:
            self.par[root_x] = root_y
            # それぞれの高さが一致する場合のみrankを更新する
            if self.rank[root_x] == self.rank[root_y]:
                self.rank[root_y] += 1

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


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

road_ways = []
rail_ways = []

for _ in range(K):
    road_ways.append(list(map(lambda x: int(x) - 1, input().split())))
for _ in range(L):
    rail_ways.append(list(map(lambda x: int(x) - 1, input().split())))
print(road_ways, rail_ways)

# 道路、鉄道を記録するUnionFind宣言
road_unionfind = UnionFind(N)
rail_unionfind = UnionFind(N)

# UnionFindを鉄道、道路それぞれで作成
for k in range(K):
    road_unionfind.unite(road_ways[k][0], road_ways[k][1])
for l in range(L):
    rail_unionfind.unite(rail_ways[l][0], rail_ways[l][1])

ans = [0 for _ in range(N)]
for n in range(N):
    # 自分自身は必ず一致しているので１スタート
    sum = 0
    for k in range(N):
        # 鉄道、道路のどちらでも繋がっているならインクリメント
        if road_unionfind.same(n, k) and rail_unionfind.same(n, k):
            sum += 1
    ans[n] = sum

print(*ans)

Submission status: Wrong Answer

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)
        
#         # 経路圧縮（のつもり）
#         self.roots[x] = root_x
#         self.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):
    # rootsにないということは、一度もconnectしてないということ
    # それであれば最終的な解答ではその街は1（自分のみ）でよいので
    # (None, None)で保存しcounterを１に変更する
    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.pick_root(i)
    rs_root = UF_rs.pick_root(i)
    
    # ある都市のpqのroot,rsのrootを保存。
    # これが両方共一致する都市は、「どちらでも連結している」といえる
    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: Wrong Answer

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)
        
        # 経路圧縮（のつもり）
        self.roots[x] = root_x
        self.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で毎回見に行くのが無駄にも思えるが、いつ根ノードがくっつくかわからないので必要な気がしている
            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):
    # rootsにないということは、一度もconnectしてないということ
    # それであれば最終的な解答ではその街は1（自分のみ）でよいので
    # (None, None)で保存しcounterを１に変更する
    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.pick_root(i)
    rs_root = UF_rs.pick_root(i)
    
    # ある都市のpqのroot,rsのrootを保存。
    # これが両方共一致する都市は、「どちらでも連結している」といえる
    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: Wrong Answer

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)
        
        # 経路圧縮（のつもり）
        self.roots[x] = root_x
        self.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で毎回見に行くのが無駄にも思えるが、いつ根ノードがくっつくかわからないので必要な気がしている
            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: Wrong Answer

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)
        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(self.roots[k])

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)))