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:
import itertools

class UnionFind:
    def __init__(self, size):
        self.parent = [-1] * (size + 1)  # 非負なら親ノード，負ならグループの要素数

    def root(self, x):  # root(x): xの根ノードを返す．
        if self.parent[x] < 0:
            return x
        elif self.parent[self.parent[x]] < 0:
            return self.parent[x]
        else:
            self.parent[x] = self.root(self.parent[x])  # xをxの根に直接つなぐ
            return self.parent[x]

    def merge(self, x, y):  # merge(x,y): xのいるグループと$y$のいるグループをまとめる
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return False
        if self.parent[x] > self.parent[y]:  # xの要素数がyの要素数より「小さい」とき入れ替える
            x, y = y, x
        self.parent[x] += self.parent[y]  # xの要素数を更新
        self.parent[y] = x  # yをxにつなぐ
        return True

    def issame(self, x, y):  # same(x,y): xとyが同じグループにあるならTrue
        return self.root(x) == self.root(y)

    def size(self, x):  # size(x): xのいるグループの要素数を返す
        return -self.parent[self.root(x)]


N,K,L = list(map(int,input().split(" ")))
tree = UnionFind(N)
anss = [1] * (N + 1 )
for _ in range(K):
    p,q = map(int,input().split(" "))
    tree.merge(p,q)
for _ in range(L):
    r, s = map(int, input().split(" "))
    if tree.issame(r,s):
        anss[r] += 1
        anss[s] += 1
print(*anss[1:])

Submission status: Wrong Answer

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N, K, L = MI()
    # UnionFind
    class UnionFind():
        def __init__(self, n):
            self.nodes=[-1] * n  # nodes[x]: 負なら、絶対値が木の要素数

        def get_root(self, x):
            # nodes[x]が負ならxが根
            if self.nodes[x] < 0:
                return x
            # 根に直接つなぎ直しつつ、親を再帰的に探す
            else:
                self.nodes[x]=self.get_root(self.nodes[x])
                return self.nodes[x]

        def unite(self, x, y):
            root_x=self.get_root(x)
            root_y=self.get_root(y)
            # 根が同じなら変わらない
            # if root_x == root_y:
            # pass
            if root_x != root_y:
                # 大きい木の方につないだほうが計算量が減る
                if self.nodes[root_x] < self.nodes[root_y]:
                    big_root=root_x
                    small_root=root_y
                else:
                    small_root=root_x
                    big_root=root_y
                self.nodes[big_root] += self.nodes[small_root]
                self.nodes[small_root]=big_root
            
        def same(self,x,y):
            return self.get_root(x)==self.get_root(y)
    uf1=UnionFind(N)
    uf2 = UnionFind(N)
    uf_both = UnionFind(N)
    for _ in range(K):
        p, q = MI_()
        uf1.unite(p, q)
        
    for _ in range(L):
        r, s = MI_()
        uf2.unite(r, s)
        if uf1.same(r,s):
            uf_both.unite(r,s)
    
    print(*[-uf_both.nodes[uf_both.get_root(i)] for i in range(N)])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

from collections import defaultdict
dic1 = defaultdict(int)
dic2 = defaultdict(int)
for _ in range(k):
   p,q = map(int,input().split())
   dic1[p] = 1
   dic1[q] = 1

for _ in range(l):
   r,s = map(int,input().split())
   dic2[r] = 1
   dic2[s] = 1


for i in range(1,n+1):
   print(dic1[i] + dic2[i])

Submission status: Wrong Answer

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

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

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

        if x == y:
            return

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

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


N, K, L = map(int, input().split())
uf = UnionFind(2 * N)
for _ in range(K):
    p, q = map(int, input().split())
    uf.union(p - 1, q - 1)

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


for i in range(N):
    cnt = 0
    for j in range(i, N):
        if uf.find(i) == uf.find(j) and uf.find(i + N) == uf.find(j + N):
            cnt += 1
    print(cnt, end=' ')

print('')

Submission status: Wrong Answer

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


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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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


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

ufl = UnionFind(N)
uft = UnionFind(N)

for _ in range(K):
    p, q = map(int, readline().split())

    ufl.union(p-1, q-1)

for _ in range(L):
    r, s = map(int, readline().split())

    if ufl.find(r-1) == ufl.find(s-1):
        uft.union(r-1, s-1)

# print(uft.all_group_members())

cnts = [0] * N

for i in range(N):
    cnts[i] = uft.size(i)

print(' '.join(map(str, cnts)))

Submission status: Wrong Answer

Solution code:
import sys

n, k, l = map(int, sys.stdin.readline().split())
roads = [tuple(map(lambda x: int(x) - 1, sys.stdin.readline().split())) for _ in range(k)]
railways = [tuple(map(lambda x: int(x) - 1, sys.stdin.readline().split())) for _ in range(l)]

reach_road = [set([i]) for i in range(n)]
reach_rail = [set([i]) for i in range(n)]

def union(v, u, kind):
    if kind == 'ro':
        reach_road[v] |= reach_road[u] 
        reach_road[u] = reach_road[v]
    elif kind == 'ra':
        reach_rail[v] |= reach_rail[u]
        reach_rail[u] = reach_rail[v]

def main():
    for v, u in roads:
        union(v, u, 'ro')
    
    for v, u in railways:
        union(v, u, 'ra')

    res = [None] * n
    for i in range(n):
        res[i] = len(reach_road[i] & reach_rail[i])
    return res

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

Submission status: Wrong Answer

Solution code:
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)]

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

u1 = UnionFind(n)
for i in range(k):
    u1.union(pq[i][0], pq[i][1])

u2 = UnionFind(n)
for i in range(l):
    u2.union(rs[i][0], rs[i][1])

for i in range(n):
    a = u1.find(i + 1)
    b = u2.find(i + 1)

from collections import defaultdict
d = defaultdict(list)
for i in range(1, len(u1.par)):
    d[str(u1.par[i]) + str(u2.par[i])].append(i)

ans = [0] * n
for k in d.keys():
    for v in d[k]:
        ans[v - 1] = len(d[k])

ans2 = ''
for i in range(len(ans)):
    ans2 += str(ans[i]) + ' '

print(ans2[:-1])

Submission status: Wrong Answer

Solution code:
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)]

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

u1 = UnionFind(n)
for i in range(k):
    u1.union(pq[i][0], pq[i][1])

u2 = UnionFind(n)
for i in range(l):
    u2.union(rs[i][0], rs[i][1])

from collections import defaultdict
d = defaultdict(list)
for i in range(1, len(u1.par)):
    d[str(u1.par[i]) + str(u2.par[i])].append(i)

ans = [0] * n
for k in d.keys():
    for v in d[k]:
        ans[v - 1] = len(d[k])

ans2 = ''
for i in range(len(ans)):
    ans2 += str(ans[i]) + ' '

print(ans2[:-1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
if sys.platform in (['ios','darwin','win32']):
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

class UnionFind():
	def __init__(self, n):
		self.n = n
		self.par = [[-1] * n for _ in range(2)]
		self.both = [[i] for i in range(n)]
	
	def root(self, t, x):
		if self.par[t][x] < 0:
			return x
		else:
			self.par[t][x] = self.root(t, self.par[t][x])
			return self.par[t][x]

	def unite(self, t, x, y):
		x, y = self.root(t, x), self.root(t, y)
		if x==y: return

		if self.par[t][x] > self.par[t][y]:
			x, y = y, x
		self.par[t][x] += self.par[t][y]
		self.par[t][y] = x

		if self.same(not t, x, y):
			self.both[x].append(y)
			self.both[y].append(x)
	
	def same(self, t, x, y):
		return self.root(t, x) == self.root(t, y)

N, K, L = MAP()
 
uf = UnionFind(N)

for _ in range(K):
	x, y = MAP()
	uf.unite(0, x-1, y-1)
 
for _ in range(L):
	x, y = MAP()
	uf.unite(1, x-1, y-1)

for i in range(N):
	print(len(set(uf.both[uf.root(0, i)])),end=' ')
else:
	print()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
if sys.platform in (['ios','darwin','win32']):
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

class UnionFind():
	def __init__(self, n):
		self.n = n
		self.par = [[-1] * n for _ in range(2)]
		self.both = [[i] for i in range(n)]
	
	def root(self, t, x):
		if self.par[t][x] < 0:
			return x
		else:
			self.par[t][x] = self.root(t, self.par[t][x])
			return self.par[t][x]

	def unite(self, t, x, y):
		x, y = self.root(t, x), self.root(t, y)
		if x==y: return

		if self.par[t][x] > self.par[t][y]:
			x, y = y, x
		self.par[t][x] += self.par[t][y]
		self.par[t][y] = x

		if self.same(not t, x, y):
			self.both[x].append(y)
			self.both[y].append(x)
	
	def same(self, t, x, y):
		return self.root(t, x) == self.root(t, y)

N, K, L = MAP()
 
uf = UnionFind(N)

for _ in range(K):
	x, y = MAP()
	uf.unite(0, x-1, y-1)
 
for _ in range(L):
	x, y = MAP()
	uf.unite(1, x-1, y-1)

for i in range(N):
	print(len(set(uf.both[i])),end=' ')
else:
	print()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
if sys.platform in (['ios','darwin','win32']):
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

class UnionFind():
	def __init__(self, n):
		self.n = n
		self.par = [[-1] * n for _ in range(2)]
		self.size = [1] * n
	
	def root(self, t, x):
		if self.par[t][x] < 0:
			return x
		else:
			self.par[t][x] = self.root(t, self.par[t][x])
			return self.par[t][x]

	def unite(self, t, x, y):
		x, y = self.root(t, x), self.root(t, y)
		if x==y: return

		if self.par[t][x] > self.par[t][y]:
			x, y = y, x
		self.par[t][x] += self.par[t][y]
		self.par[t][y] = x

		if self.same(not t, x, y):
			self.size[x] += 1
			self.size[y] += 1
	
	def same(self, t, x, y):
		return self.root(t, x) == self.root(t, y)
	
	def size(self, t, x):
		return -self.par[t][self.root(t, x)]

N, K, L = MAP()
 
uf = UnionFind(N)

for _ in range(K):
	x, y = MAP()
	uf.unite(0, x-1, y-1)
 
for _ in range(L):
	x, y = MAP()
	uf.unite(1, x-1, y-1)

print(' '.join(map(str, uf.size)))

Submission status: Wrong Answer

Solution code:
# 参考URL
# https://note.nkmk.me/python-union-find/
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

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

        if x == y:
            return

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

        self.parents[x] += self.parents[y]
        self.parents[y] = x
        
    def same(self, x, y):
        return self.find(x) == self.find(y)

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


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

uf_road = UnionFind(N)

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

ans = [1]*N
for i in range(L):
    a, b = map(int, input().split())
    if uf_road.same(a-1, b-1):
        ans[a-1]+=1
        ans[b-1]+=1
    
print(' '.join(map(str, ans)))

Submission status: Wrong Answer

Solution code:
def col(n, E):
    C = [-1] * n
    c = 0
    for i in range(N):
        if C[i] >= 0: continue
        Q = [i]
        C[i] = c
        while Q:
            x = Q.pop()
            for y in E[x]:
                if C[y] == -1:
                    C[y] = C[x]
                    Q.append(y)
        c += 1
    return C

N, K, L = map(int, input().split())
X = [[] for _ in range(N)]
Y = [[] for _ in range(N)]
for _ in range(K):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    X[a].append(b)
    X[b].append(a)
XX = col(N, X)
for _ in range(L):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    if XX[a] == XX[b]:
        Y[a].append(b)
        Y[b].append(a)
YY = col(N, Y)
D = [0] * N
for y in YY:
    D[y] += 1

print(*[D[y] for y in YY])

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self,N):
        self.parent = [i for i in range(N)]
        self.rank = [0] * N
        self.count = 0
    def root(self,a):
        if self.parent[a] == a:
            return a
        else:
            self.parent[a] = self.root(self.parent[a])
            return self.parent[a]
    def is_same(self,a,b):
        return self.root(a) == self.root(b)
    def unite(self,a,b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb: return
        if self.rank[ra] < self.rank[rb]:
            self.parent[ra] = rb
        else:
            self.parent[rb] = ra
            if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1
        self.count += 1
    
N,K,L = map(int,input().split())
road = []
train = []
for i in range(K):
    p,q = map(int,input().split())
    p -= 1
    q -= 1
    road.append([p,q])
for i in range(L):
    r,s = map(int,input().split())
    r -= 1
    s -= 1
    train.append([r,s])

uf = UnionFind(N)
ans = [1]*N
for p,q in road:
    uf.unite(p,q)
for r,s in train:
    if uf.is_same(r,s):
        ans[r] += 1
        ans[s] += 1
print(*ans)

Submission status: Wrong Answer

Solution code:
import collections

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

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

def solve():
 n,k,l = (int(i) for i in input().split())
 ufr = UnionFind(n-1)
 for i in range(k):
   tmp1,tmp2 = (int(i) for i in input().split())
   ufr.union(tmp1-1,tmp2-1)
 uft = UnionFind(n-1)
 for i in range(l):
   tmp1,tmp2 = (int(i) for i in input().split())
   uft.union(tmp1-1,tmp2-1)
 query = []
 for i in range(n):
    query.append((ufr.par[i],uft.par[i]))
 c = collections.Counter(query)
 ans = []
 for i in range(n):
  ans.append(c[query[i]])
 print(*ans)

solve()

Submission status: Wrong Answer

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

class UnionFind():
  def __init__(self):
    self.par = [i for i in range(N)]

  def root(self, x):
    if self.par[x] == x:
      return x
    else:
      self.par[x] = self.root(self.par[x])
      return self.par[x]
  
  def unite(self, x, y):
    self.par[self.root(y)] = self.root(x)
    self.root(y)


ufRoad = UnionFind()

for i in range(K):
  p, q = map(int, input().split())
  ufRoad.unite(p-1, q-1)

ufRail = UnionFind()

for i in range(L):
  r, s = map(int, input().split())
  ufRail.unite(r-1, s-1)

SRoad = {}
SRail = {}

for i in range(N):
  SRoad[ufRoad.par[i]] = SRoad.get(ufRoad.par[i], set()) | {i}  
  SRail[ufRail.par[i]] = SRail.get(ufRail.par[i], set()) | {i}

r = [0] * N
for i in range(N):
  r[i] = len(SRoad.get(ufRoad.par[i], set()) & SRail.get(ufRail.par[i], set()))

print(*r)

Submission status: Wrong Answer

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

class UnionFind():
  def __init__(self):
    self.par = [i for i in range(N)]

  def root(self, x):
    if self.par[x] == x:
      return x
    else:
      self.par[x] = self.root(self.par[x])
      return self.par[x]
  
  def unite(self, x, y):
    self.par[self.root(y)] = self.root(x)
    self.root(y)


ufRoad = UnionFind()

for i in range(K):
  p, q = map(int, input().split())
  ufRoad.unite(p-1, q-1)

ufRail = UnionFind()

for i in range(L):
  r, s = map(int, input().split())
  ufRail.unite(r-1, s-1)

SRoad = {}
SRail = {}

for i in range(N):
  SRoad[ufRoad.par[i]] = SRoad.get(ufRoad.par[i], set()) | {i}  
  SRail[ufRail.par[i]] = SRail.get(ufRail.par[i], set()) | {i}

r = [0] * N
for i in range(N):
  r[i] = len(SRoad.get(ufRoad.par[i], set()) & SRail.get(ufRail.par[i], set()))

print(r)

Submission status: Wrong Answer

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

class UnionFind():
  def __init__(self):
    self.par = [i for i in range(N)]

  def root(self, x):
    if self.par[x] == x:
      return x
    else:
      self.par[x] = self.root(self.par[x])
      return self.par[x]
  
  def unite(self, x, y):
    self.par[self.root(y)] = self.root(x)
    self.root(y)


ufRoad = UnionFind()

for i in range(K):
  p, q = map(int, input().split())
  ufRoad.unite(p-1, q-1)

ufRail = UnionFind()

for i in range(L):
  r, s = map(int, input().split())
  ufRail.unite(r-1, s-1)

SRoad = [set() for i in range(N)]
SRail = [set() for i in range(N)]

for i in range(N):
  SRoad[ufRoad.par[i]].add(i)
  SRail[ufRail.par[i]].add(i)

r = [0] * N
for i in range(N):
  r[i] = len(SRoad[ufRoad.par[i]] & SRail[ufRail.par[i]])

print(*r)

Submission status: Wrong Answer

Solution code:
N,K,L=map(int,input().split())
PQ=[list(map(int,input().split())) for i in range(K)]
RS=[list(map(int,input().split())) for i in range(L)]

import sys

def find_root(root,x):
    y = root[x]
    if x == y:
        return x
    z = find_root(root,y)
    root[x] = z
    return z
 
def merge(root,size,x,y):
    x = find_root(root,x)
    y = find_root(root,y)
    if x == y:
        return
    sx,sy = size[x],size[y]
    if sx < sy:
        sx,sy = sy,sx
        x,y = y,x
    root[y] = x
    size[x] += sy
    
def UF_make(graph,n):
    Root=list(range(n+1))
    Size=[1] * (n+1)
    for i in range(len(graph)):
        merge(Root,Size,graph[i][0],graph[i][1])
    for i in range(n+1):
        Root[i] = find_root(Root,i)
    Root.pop(0)  #
    return Root

PQN=UF_make(PQ,N)
RSN=UF_make(RS,N)

if K+L<=10 and N<=5:
    PQRS=[]
    for i in range(N):
        PQRS.append([PQN[i],RSN[i]])
    ans=[1]*N
    for i in range(N):
        ans[i]=PQRS.count(PQRS[i])
    print(*ans)
    sys.exit()

PQRS=[PQN[i]*10**6+RSN[i] for i in range(N)]
D=len(set(PQRS))
PQRS=[[PQRS[i],i,0] for i in range(N)]
PQRS.sort()

p=0
if D==1:
    PPQQ=[]
    for i in range(K):
        PPQQ.append(PQ[i][0])
        PPQQ.append(PQ[i][1])
    T=[PPQQ.count(i)+1 for i in range(1,N+1)]
    print(*T)
else:
    while p<N:
        i=1
        c=0
        if p+i>=N-1:
            break
        while PQRS[p][0]==PQRS[p+i][0]:
            c+=1
            i+=1
        for j in range(p,p+i):
            PQRS[j][2]=c
        p+=i
    PQRS.sort(key=lambda x:x[1])
    for i in range(N):
        print(PQRS[i][2]+1,end=' ')

Submission status: Wrong Answer

Solution code:
N,K,L=map(int,input().split())
PQ=[list(map(int,input().split())) for i in range(K)]
RS=[list(map(int,input().split())) for i in range(L)]

import sys

def find_root(root,x):
    y = root[x]
    if x == y:
        return x
    z = find_root(root,y)
    root[x] = z
    return z
 
def merge(root,size,x,y):
    x = find_root(root,x)
    y = find_root(root,y)
    if x == y:
        return
    sx,sy = size[x],size[y]
    if sx < sy:
        sx,sy = sy,sx
        x,y = y,x
    root[y] = x
    size[x] += sy
    
def UF_make(graph,n):
    Root=list(range(n+1))
    Size=[1] * (n+1)
    for i in range(len(graph)):
        merge(Root,Size,graph[i][0],graph[i][1])
    for i in range(n+1):
        Root[i] = find_root(Root,i)
    Root.pop(0)  #
    return Root

PQN=UF_make(PQ,N)
RSN=UF_make(RS,N)

if N<=5:
    PQRS=[]
    for i in range(N):
        PQRS.append([PQN[i],RSN[i]])
    ans=[1]*N
    for i in range(N):
        ans[i]=PQRS.count(PQRS[i])
    print(*ans)
    sys.exit()

PQRS=[PQN[i]*10**6+RSN[i] for i in range(N)]
D=len(set(PQRS))
PQRS=[[PQRS[i],i,0] for i in range(N)]
PQRS.sort()

p=0
if D==1:
    PPQQ=[]
    for i in range(K):
        PPQQ.append(PQ[i][0])
        PPQQ.append(PQ[i][1])
    T=[PPQQ.count(i)+1 for i in range(1,N+1)]
    print(*T)
else:
    while p<N:
        i=1
        c=0
        if p+i>=N-1:
            break
        while PQRS[p][0]==PQRS[p+i][0]:
            c+=1
            i+=1
        for j in range(p,p+i):
            PQRS[j][2]=c
        p+=i
    PQRS.sort(key=lambda x:x[1])
    for i in range(N):
        print(PQRS[i][2]+1,end=' ')

Submission status: Wrong Answer

Solution code:
N,K,L=map(int,input().split())
PQ=[list(map(int,input().split())) for i in range(K)]
RS=[list(map(int,input().split())) for i in range(L)]

def find_root(root,x):
    y = root[x]
    if x == y:
        return x
    z = find_root(root,y)
    root[x] = z
    return z
 
def merge(root,size,x,y):
    x = find_root(root,x)
    y = find_root(root,y)
    if x == y:
        return
    sx,sy = size[x],size[y]
    if sx < sy:
        sx,sy = sy,sx
        x,y = y,x
    root[y] = x
    size[x] += sy
    
def UF_make(graph,n):
    Root=list(range(n+1))
    Size=[1] * (n+1)
    for i in range(len(graph)):
        merge(Root,Size,graph[i][0],graph[i][1])
    for i in range(n+1):
        Root[i] = find_root(Root,i)
    Root.pop(0)  #
    return Root

PQN=UF_make(PQ,N)
RSN=UF_make(RS,N)
PQRS=[PQN[i]*10**6+RSN[i] for i in range(N)]
D=len(set(PQRS))
PQRS=[[PQRS[i],i,0] for i in range(N)]
PQRS.sort()

p=0
if D==1:
    PPQQ=[]
    for i in range(K):
        PPQQ.append(PQ[i][0])
        PPQQ.append(PQ[i][1])
    T=[PPQQ.count(i)+1 for i in range(1,N+1)]
    print(*T)
else:
    while p<N:
        i=1
        c=0
        if p+i>=N-1:
            break
        while PQRS[p][0]==PQRS[p+i][0]:
            c+=1
            i+=1
        for j in range(p,p+i):
            PQRS[j][2]=c
        p+=i
    PQRS.sort(key=lambda x:x[1])
    for i in range(N):
        print(PQRS[i][2]+1,end=' ')

Submission status: Wrong Answer

Solution code:
N,K,L=map(int,input().split())
PQ=[list(map(int,input().split())) for i in range(K)]
RS=[list(map(int,input().split())) for i in range(L)]

def find_root(root,x):
    y = root[x]
    if x == y:
        return x
    z = find_root(root,y)
    root[x] = z
    return z
 
def merge(root,size,x,y):
    x = find_root(root,x)
    y = find_root(root,y)
    if x == y:
        return
    sx,sy = size[x],size[y]
    if sx < sy:
        sx,sy = sy,sx
        x,y = y,x
    root[y] = x
    size[x] += sy
    
def UF_make(graph,n):
    Root=list(range(n+1))
    Size=[1] * (n+1)
    for i in range(len(graph)):
        merge(Root,Size,graph[i][0],graph[i][1])
    for i in range(n+1):
        Root[i] = find_root(Root,i)
    Root.pop(0)  #
    return Root

PQN=UF_make(PQ,N)
RSN=UF_make(RS,N)
PQRS=[PQN[i]*10**6+RSN[i] for i in range(N)]
D=len(set(PQRS))
PQRS=[[PQRS[i],i,0] for i in range(N)]
PQRS.sort()

p=0
if D==1:
    print(*[N]*N)
else:
    while p<N:
        i=1
        c=0
        if p+i>=N-1:
            break
        while PQRS[p][0]==PQRS[p+i][0]:
            c+=1
            i+=1
        for j in range(p,p+i):
            PQRS[j][2]=c
        p+=i
    PQRS.sort(key=lambda x:x[1])
    for i in range(N):
        print(PQRS[i][2]+1,end=' ')

Submission status: Wrong Answer

Solution code:
N,K,L=map(int,input().split())
PQ=[list(map(int,input().split())) for i in range(K)]
RS=[list(map(int,input().split())) for i in range(L)]

def find_root(root,x):
    y = root[x]
    if x == y:
        return x
    z = find_root(root,y)
    root[x] = z
    return z
 
def merge(root,size,x,y):
    x = find_root(root,x)
    y = find_root(root,y)
    if x == y:
        return
    sx,sy = size[x],size[y]
    if sx < sy:
        sx,sy = sy,sx
        x,y = y,x
    root[y] = x
    size[x] += sy
    
def UF_make(graph,n):
    Root=list(range(n+1))
    Size=[1] * (n+1)
    for i in range(len(graph)):
        merge(Root,Size,graph[i][0],graph[i][1])
    for i in range(n+1):
        Root[i] = find_root(Root,i)
    Root.pop(0)
    return Root

PQN=UF_make(PQ,N)
RSN=UF_make(RS,N)
PQRS=[]
for i in range(N):
    PQRS.append([PQN[i],RSN[i]])

ans=[1]*N
for i in range(N):
    ans[i]=PQRS.count(PQRS[i])
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import sys

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


def root(par, x):
    if par[x] == x:
        return x
    else:
        return root(par, par[x])


def same(par, x, y):
    return root(par, x) == root(par, y)


def unite(rank, par, x, y):
    x = root(par, x)
    y = root(par, y)

    if x == y:
        return

    if rank[x] < rank[y]:
        par[x] = y
    else:
        par[y] = x
        if rank[x] == rank[y]:
            rank[x] += 1


def main():
    N, K, L = map(int, readline().split())
    m = map(int, read().split())
    pq = list(zip(m, m))
    pq, rs = pq[:K], pq[K:]

    d_c = defaultdict(list)
    d_t = defaultdict(list)

    par = list(range(N))
    rank = [0] * N
    for p, q in pq:
        p -= 1
        q -= 1
        unite(rank, par, p, q)

    for i in range(N):
        par[i] = root(par, i)

    par_t = list(range(N))
    rank_t = [0] * N
    for r, s in rs:
        r -= 1
        s -= 1
        unite(rank_t, par_t, r, s)

    for i in range(N):
        par_t[i] = root(par_t, i)

    for i in range(N):
        d_c[par[i]].append(i)
        d_t[par_t[i]].append(i)

    for i in range(N):
        d_c[i] = d_c[par[i]]
        d_t[i] = d_t[par_t[i]]

    cnt = [0] * N
    for i in range(N):
        cnt[i] = len(list(set(d_c[i]) & set(d_t[i])))
        print(list(set(d_c[i]) & set(d_t[i])))

    print(*cnt)


main()