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

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
from itertools import groupby
def resolve():
    n,k,l=map(int,input().split())
    K=[[] for _ in range(n)]
    L=[[] for _ in range(n)]
    for _ in range(k):
        p,q=map(int,input().split())
        p-=1; q-=1
        K[p].append(q)
        K[q].append(p)
    for _ in range(l):
        r,s=map(int,input().split())
        r-=1; s-=1
        L[r].append(s)
        L[s].append(r)

    
    C1=[-1]*n
    col=0
    def dfs1(v)->bool:
        if(C1[v]!=-1): return False
        C1[v]=col
        Q=[v]
        while(Q):
            v=Q.pop()
            for nv in K[v]:
                if(C1[nv]!=-1): continue
                C1[nv]=col
                Q.append(nv)
        return True

    for v in range(n):
        col+=dfs1(v)

    
    C2=[-1]*n
    col=0
    def dfs2(v)->bool:
        if(C2[v]!=-1): return False
        C2[v]=col
        Q=[v]
        while(Q):
            v=Q.pop()
            for nv in L[v]:
                if(C2[nv]!=-1): continue
                C2[nv]=col
                Q.append(nv)
        return True

    for v in range(n):
        col+=dfs2(v)

    ans=[None]*n
    X=[(C1[v],C2[v],v) for v in range(n)]
    X.sort()
    for key,iter in groupby(X,key=lambda x:(x[0],x[1])):
        s=list(iter)
        for a,b,c in s:
            ans[c]=len(s)
    print(*ans)
resolve()

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
from itertools import groupby
def resolve():
    n,k,l=map(int,input().split())
    K=[[] for _ in range(n)]
    L=[[] for _ in range(n)]
    for _ in range(k):
        p,q=map(int,input().split())
        p-=1; q-=1
        K[p].append(q)
        K[q].append(p)
    for _ in range(l):
        r,s=map(int,input().split())
        r-=1; s-=1
        L[r].append(s)
        L[s].append(r)

    
    C1=[-1]*n
    col=[0]
    def dfs1(v)->bool:
        if(C1[v]!=-1): return False
        C1[v]=col[0]
        Q=[v]
        while(Q):
            v=Q.pop()
            for nv in K[v]:
                if(C1[nv]!=-1): continue
                C1[nv]=col[0]
                Q.append(nv)
        return True

    for v in range(n):
        col[0]+=dfs1(v)

    
    C2=[-1]*n
    col=[0]
    def dfs2(v)->bool:
        if(C2[v]!=-1): return False
        C2[v]=col[0]
        Q=[v]
        while(Q):
            v=Q.pop()
            for nv in L[v]:
                if(C2[nv]!=-1): continue
                C2[nv]=col[0]
                Q.append(nv)
        return True

    for v in range(n):
        col[0]+=dfs2(v)

    ans=[None]*n
    X=[(C1[v],C2[v],v) for v in range(n)]
    X.sort()
    for key,iter in groupby(X,key=lambda x:(x[0],x[1])):
        s=list(iter)
        for a,b,c in s:
            ans[c]=len(s)
    print(*ans)
resolve()

Solution (Python):
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 __ser__(self):
        return '\n'.join('{}: {}'.format(r, sself.members(r)) for r in self.roots())

n,k,l = map(int, input().split())
a = Unionfind(n)
b = Unionfind(n)
for i in range(k):
    p,q = map(int, input().split())
    p -=1
    q -=1
    a.union(p,q)

for i in range(l):
    r,s = map(int, input().split())
    r-=1
    s-=1
    b.union(r,s)

c = [(a.find(x),b.find(x)) for x in range(n)]
count = {}
for i in c:
    if i in count:
        count[i]+=1
    else:
        count[i] = 1
print(*[count[i] for i in c])

Solution (Python):
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)

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)

d = {}

for i in range(N):
  d[(ufRoad.root(i), ufRail.root(i))] = d.get((ufRoad.root(i), ufRail.root(i)), 0) + 1

r = [0] * N

for i in range(N):
  r[i] = d.get((ufRoad.root(i), ufRail.root(i)))

print(*r)

Solution (Python):
from itertools import combinations
from collections import Counter
class UnionFind():
  def __init__(self, x):
    self.x=x
    self.root=[-1]*(N+1)
    self.rnk=[0]*(N+1)
  
  def Find_root(self, x):
    if self.root[x]<0:
      return x
    else:
      self.root[x]=self.Find_root(self.root[x])
      return self.root[x]
    
  def Unite(self, x, y):
    x = self.Find_root(x)
    y = self.Find_root(y)
    if x==y:
      return
    elif self.rnk[x]>self.rnk[y]:
      self.root[x] += self.root[y]
      self.root[y] = x
    else:
      self.root[y] += self.root[x]
      self.root[x] = y
      if self.rnk[x]==self.rnk[y]:
        self.rnk[y]+=1
  
  def isSameGroup(self, x, y):
    return self.Find_root(x)==self.Find_root(y)
  
  def Count(self, x):
    return -self.root[self.Find_root(x)]
N,K,L=map(int,input().split())
u1=UnionFind(N)
u2=UnionFind(N)
for _ in range(K):
  x,y=map(int,input().split())
  u1.Unite(x-1,y-1)
for _ in range(L):
  x,y=map(int,input().split())
  u2.Unite(x-1,y-1)
l=[]
for i in range(N):
  l.append((u1.Find_root(i), u2.Find_root(i)))
c = Counter(l)
ans = []
for i in range(N):
  ans.append(c[(u1.Find_root(i), u2.Find_root(i))])
print(*ans)

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


class UnionFind():
    def __init__(self, n):
        self.tree = [i for i in range(n)]

    def root(self, x):
        if(self.tree[x] == x):
            return x
        self.tree[x] = self.root(self.tree[x])
        return self.tree[x]  

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

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


uf = UnionFind(n)
uf2 = UnionFind(n)

for _ in range(k):
    p, q = map(int, input().split())
    uf.unite(q-1, p-1)
for _ in range(l):
    r, s = map(int, input().split())
    uf2.unite(s-1, r-1)


table = dict()

for i in range(n):
    
    table[(uf.root(i), uf2.root(i))] = table.get(
        (uf.root(i), uf2.root(i)), 0)+1
for i in range(n):
    print(table[(uf.root(i), uf2.root(i))], end=' ')

exit(0)
for i, j in [(uf.root(i), uf2.root(i)) for i in range(n)]:
    table[i][j] += 1
for i, j in [(uf.root(i), uf2.root(i)) for i in range(n)]:
    print(table[i][j], end=' ')


exit(0)
for i in range(n):
    ans = 0
    for j in range(n):
        if uf.same(i, j) and uf2.same(i, j):
            ans += 1
    print(ans, end=' ')

Solution (Python):
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
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
        if p+i>N-1:
            break
    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=' ')

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect_left
import heapq

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, K, L = MAP()
pq = [LIST() for _ in range(K)]
rs = [LIST() 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)

tree_road = UnionFind(N)
tree_train = UnionFind(N)
for p, q in pq:
	tree_road.union(p, q)

for r, s in rs:
	tree_train.union(r, s)

dic = defaultdict(int)
for i in range(1, N+1):
	dic[(tree_road.find(i), tree_train.find(i))] += 1

for i in range(1, N+1):
	print(dic[(tree_road.find(i), tree_train.find(i))], end=" ")

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect_left
import heapq

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, K, L = MAP()
pq = [LIST() for _ in range(K)]
rs = [LIST() 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)

tree_road = UnionFind(N)
tree_train = UnionFind(N)
for p, q in pq:
	tree_road.union(p, q)

for r, s in rs:
	tree_train.union(r, s)

dic = defaultdict(int)
for i in range(1, N+1):
	dic["({},{})".format(tree_road.find(i), tree_train.find(i))] += 1

for i in range(1, N+1):
	print(dic["({},{})".format(tree_road.find(i), tree_train.find(i))], end=" ")

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

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

    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)

    pp = [(0, 0)]*N
    dd = defaultdict(list)
    for i in range(N):
        par[i] = root(par, i)
        par_t[i] = root(par_t, i)
        pp[i] = (par[i], par_t[i])
        dd[pp[i]].append(i)

    cnt = [0] * N
    for i in range(N):
        cnt[i] = len(dd[pp[i]])

    print(*cnt)


main()

Solution (Python):
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(self, x, y):
        return self.find(x) == self.find(y)


from collections import deque

def solve():
    N, K, L = tuple(map(int, input().split()))

    PQ = []
    for _ in range(K):
        PQ.append(tuple(map(int, input().split())))
    RS = []
    for _ in range(L):
        RS.append(tuple(map(int, input().split())))

    
    
    

    road = UnionFind(10**5*2 + 1)
    rail = UnionFind(10**5*2 + 1)

    for a, b in PQ:
        road.union(a, b)

    for a, b in RS:
        rail.union(a, b)

    d = {}
    for i in range(N):
        i += 1
        road_root = road.find(i)
        rail_root = rail.find(i)
        if not (road_root, rail_root) in d:
            d[(road_root, rail_root)] = 1
        else:
            d[(road_root, rail_root)] += 1

    ans = deque()
    for i in range(N):
        i += 1
        road_root = road.find(i)
        rail_root = rail.find(i)
        ans.append(d[(road_root, rail_root)])

    return " ".join(tuple(map(str, ans)))


if __name__ == '__main__':
    res = solve()
    print(res)

Solution (Python):

import bisect
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)]


class UF:
    def __init__(self,n):
        self.n = n
        self.root = [-1]*n 
        self.rank = [0]*n 
    def __del__(self):
        pass
        
    def find(self,x):
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]
            
    def unite(self,x,y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        
        if self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x]+=1
                
    def same(self,x,y):
        return self.find(x) == self.find(y) 
    
    def count(self,x):
        return -self.root[self.find(x)]
    
uf1 = UF(N)
for pq in PQ:
    p,q = pq
    uf1.unite(p-1,q-1)
ar = [0]*N
uff1 = [uf1.find(i) for i in range(N)]
for i,u in enumerate(uff1):
    if u < 0:
        ar[i] = i
    else:
        ar[i] = u

uf2 = UF(N)
for rs in RS:
    r,s = rs
    uf2.unite(r-1,s-1)
br = [0]*N
uff2 = [uf2.find(i) for i in range(N)]
for i,u in enumerate(uff2):
    if u < 0:
        br[i] = i
    else:
        br[i] = u

cr = [[ar[i],br[i]] for i in range(N)]
dr = cr[::]
dr.sort()
for c in cr:
    ans = bisect.bisect_right(dr,c) - bisect.bisect_left(dr,c)
    print(ans,end=" ")

Solution (Python):
class UnionFind:
    def __init__(self, n):
        self.par = list(range(n))
        self.rank = [0] * n
        self.size = [1] * n

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

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

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

    def get_size(self, x):
        return self.size[self.find(x)]
      
from collections import Counter


def abc049_d():
    n, k, l = map(int, input().split())

    road = UnionFind(n)
    for i in range(k):
        p, q = map(int, input().split())
        road.unite(p - 1, q - 1)

    rail = UnionFind(n)
    for i in range(l):
        r, s = map(int, input().split())
        rail.unite(r - 1, s - 1)

    set1 = []
    for i in range(n):
        set1.append((road.find(i), rail.find(i)))
    c = Counter(set1)
    ans = []
    for i in range(n):
        ans.append(c[(road.find(i), rail.find(i))])
    print(*ans)


if __name__ == '__main__':
    abc049_d()

Solution (Python):
class UnionFind:
    def __init__(self, n):
        self.par = list(range(n))
        self.rank = [0] * n
        self.size = [1] * n

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

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

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

    def get_size(self, x):
        return self.size[self.find(x)]
      
from collections import Counter


def abc049_d():
    n, k, l = map(int, input().split())

    road = UnionFind(n)
    for i in range(k):
        p, q = map(int, input().split())
        road.unite(p - 1, q - 1)

    rail = UnionFind(n)
    for i in range(l):
        r, s = map(int, input().split())
        rail.unite(r - 1, s - 1)

    set1 = []
    for i in range(n):
        set1.append((road.find(i), rail.find(i)))
    c = Counter(set1)
    ans = []
    for i in range(n):
        ans.append(c[(road.find(i), rail.find(i))])
    print(*ans)


if __name__ == '__main__':
    abc049_d()

Solution (Python):
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())
ufK = UnionFind(N)
ufL = UnionFind(N)
ans = [1]*(N)
for i in range(K):
    p,q = map(int,input().split())
    ufK.union(p-1,q-1)
for i in range(L):
    r,s = map(int,input().split())
    ufL.union(r-1,s-1)
from collections import defaultdict
ar=[(ufK.find(i),ufL.find(i)) for i in range(N)]
dic=defaultdict(int)
 
for i in ar:
    dic[i]+=1
ans=[]
for i in range(N):
    ans.append(dic[ar[i]])
print(*ans)

Solution (Python):
import sys
from collections import defaultdict
sys.setrecursionlimit(10**7)

class UnionFind():
    def __init__(self, N):
        self.N = N
        self.par = [n for n in range(N)]
        self.rank = [0 for _ in range(N)]

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

    def union(self, x, y):
        x = self.find(self.par[x])
        y = self.find(self.par[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 isSame(self, x, y):
        return self.par[x] == self.par[y]

    def refresh(self):
        for p in range(N):
            self.find(p)

N, K, L = [int(x) for x in input().strip().split()]
road = UnionFind(N)
train = UnionFind(N)

for ｋ in range(K):
    p, q = [int(x) - 1 for x in input().strip().split()]
    road.union(p, q)
for l in range(L):
    r, s = [int(x) - 1 for x in input().strip().split()]
    train.union(r, s)

d = defaultdict(int)
for n in range(N):
    r = road.find(n)
    t = train.find(n)
    d[(r, t)] += 1

for n in range(N):
    print(d[(road.par[n], train.par[n])], end=' ')

Solution (Python):
import sys
from collections import defaultdict
sys.setrecursionlimit(10**7)

class UnionFind():
    def __init__(self, N):
        self.N = N
        self.par = [n for n in range(N)]
        self.rank = [0 for _ in range(N)]

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

    def union(self, x, y):
        x = self.find(self.par[x])
        y = self.find(self.par[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 isSame(self, x, y):
        return self.par[x] == self.par[y]

    def refresh(self):
        for p in range(N):
            self.find(p)

N, K, L = [int(x) for x in input().strip().split()]
road = UnionFind(N)
train = UnionFind(N)

for ｋ in range(K):
    p, q = [int(x) - 1 for x in input().strip().split()]
    road.union(p, q)
for l in range(L):
    r, s = [int(x) - 1 for x in input().strip().split()]
    train.union(r, s)

d = defaultdict(int)
for n in range(N):
    r = road.find(n)
    t = train.find(n)
    d[(r, t)] += 1

for n in range(N):
    print(d[(road.par[n], train.par[n])], end=' ')

Solution (Python):
import sys
from collections import defaultdict
sys.setrecursionlimit(10**7)

N, K, L = [int(x) for x in input().strip().split()]
road_par = [n for n in range(N)]
road_rank = [0 for _ in range(N)]
train_par = [n for n in range(N)]
train_rank = [0 for _ in range(N)]

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

def union(par, rank, x, y):
    x = find(par, par[x])
    y = find(par, 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

for ｋ in range(K):
    p, q = [int(x) - 1 for x in input().strip().split()]
    union(road_par, road_rank, p, q)
for l in range(L):
    r, s = [int(x) - 1 for x in input().strip().split()]
    union(train_par, train_rank, r, s)

d = defaultdict(int)
for n in range(N):
    r = find(road_par, n)
    t = find(train_par, n)
    d[(r, t)] += 1

for n in range(N):
    print(d[(road_par[n], train_par[n])], end=' ')

Solution (Python):
from collections import Counter,defaultdict,deque
import sys,bisect,math,itertools,string,queue,copy
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def inp(): 
    return int(input())
def inpm(): 
    return map(int,input().split())
def inpl(): 
    return list(map(int, input().split()))
def inpls(): 
    return list(input().split())
def inpln(n): 
    return list(int(input()) for _ in range(n))
def inpll(n): 
    return sorted([list(map(int, input().split())) for _ in range(n)])
def sortx(x,n,k):
    if k == 0:x.sort(key=lambda y:y[1,n])
    else:x.sort(reversed=True, key=lambda y:y[1,n])

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

def unite(x,y): 
    x=find(x)
    y=find(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 same(x,y): 
    return find(x)==find(y)
 
def main():
    n,k,l = inpm()
 
    global par,rank
    par  = [i for i in range(2*n)]
    rank = [-1 for _ in range(2*n)] 
    for _ in range(k):
        p,q = inpm()
        p-=1
        q-=1
        unite(p,q)
    for _ in range(l):
        r,s = inpm()
        r-=1
        s-=1
        unite(r+n,s+n)

    root_s=defaultdict(int)
    root=[]
    for i in range(n):
        root.append(str(find(i))+' '+str(find(i+n)))
        root_s[root[i]]+=1
    
    ans=[0 for _ in range(n)]
    for i in range(n):
        ans[i] = root_s[root[i]]
    print(*ans) 


if __name__ == "__main__":
    main()

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

data=[[] for i in range(n+1)]
for i in range(k):
    p,q=map(int,input().split())
    data[p].append(q)
    data[q].append(p)
parent=[0]*(n+1)
num=1
for i in range(1,n+1):
    if parent[i]==0:
        parent[i]=num
        que=[i]
        while que:
            h=que.pop()
            for u in data[h]:
                if parent[u]==0:
                    parent[u]=num
                    que.append(u)
        num+=1

data=[[] for i in range(n+1)]
for i in range(l):
    r,s=map(int,input().split())
    data[r].append(s)
    data[s].append(r)
flag=[0]*(n+1)
num=1
for i in range(1,n+1):
    if flag[i]==0:
        flag[i]=num
        que=[i]
        while que:
            h=que.pop()
            for u in data[h]:
                if flag[u]==0:
                    flag[u]=num
                    que.append(u)
        num+=1

lst=[]
for i in range(1,n+1):
    lst.append([parent[i],flag[i],i])

ans=[1]*(n+1)
lst.sort()
k=0
for i in range(1,n):
    if lst[i][:2]==lst[i-1][:2]:
        k+=1
    else:
        for j in range(i-1-k,i):
            ans[lst[j][2]]+=k
        k=0
for j in range(n-1-k,n):
    ans[lst[j][2]]+=k
print(*ans[1:])

Solution (Python):
from collections import defaultdict
class UnionFind(object):
  def __init__(self,n=1):
    self.par = [i for i in range(n)]
    self.rank = [0 for _ in range(n)]
    self.size = [1 for _ in range(n)]


  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 x != y :
      if self.rank[x] <self.rank[y]:
        x,y = y,x
      if self.rank[x] == self.rank[y]:
        self.rank[x] += 1
      self.par[y] = x
      self.size[x] +=self.size[y]

  def is_same(self,x,y):
    return self.find(x)==self.find(y)
  
  def get_size(self,x):
    x = self.find(x)
    return self.size[x]

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


uf1 = UnionFind(N)
for i in range(K):
    p, q = map(int, input().split())
    uf1.union(p - 1, q - 1)
 

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

c = defaultdict(int)
for i in range(N):
    c[(uf1.find(i), uf2.find(i))] += 1
ans = ""


for i in range(N):
    ans += str(c[(uf1.find(i), uf2.find(i))]) + " "
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline


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

    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 unite(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 is_same(self, x, y):
        return self.find(x) == self.find(y)


from collections import defaultdict
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)]


A = UnionFind(N)
for p,q in PQ:
    A.unite(p-1,q-1)


B = UnionFind(N)
for r,s in RS:
    B.unite(r-1,s-1)

dic = defaultdict(int)
for i in range(N):
    dic[A.find(i), B.find(i)] += 1

Ans = list(dic[A.find(i), B.find(i)] for i in range(N))
print(" ".join(map(str,Ans)))