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):
n,k,l=map(int,input().split())
pq=[list(map(int,input().split())) for _ in [0]*k]
rs=[list(map(int,input().split())) for _ in [0]*l]

gpq=[[] for _ in [0]*n]
[gpq[b-1].append(a-1) for a,b in pq]
[gpq[a-1].append(b-1) for a,b in pq]

grs=[[] for _ in [0]*n]
[grs[b-1].append(a-1) for a,b in rs]
[grs[a-1].append(b-1) for a,b in rs]

memo_set=set()
list_pq=[]
for i in range(n):
    if i not in memo_set:
        q=[i]
        temp_set={i}
        while q:
            qq=q.pop()
            for g in gpq[qq]:
                if g not in temp_set:
                    q.append(g)
                    temp_set.add(g)
                    memo_set.add(g)
        list_pq.append(temp_set)
        
memo_set=set()
list_rs=[]
for i in range(n):
    if i not in memo_set:
        q=[i]
        temp_set={i}
        while q:
            qq=q.pop()
            for g in grs[qq]:
                if g not in temp_set:
                    q.append(g)
                    temp_set.add(g)
                    memo_set.add(g)
        list_rs.append(temp_set)

dict_rs=dict()

for i,d in enumerate(list_rs):
    for j in d:
        dict_rs[j]=i

dict_pq=dict()

ans=[None]*n
for i,d in enumerate(list_pq):
    for j in d:
        no=dict_rs[j]
        if (i,no) in dict_pq.keys():
            ans[j]=dict_pq[(i,no)]
        else:
            a=len(d&list_rs[no])
            dict_pq[(i,no)]=a
            ans[j]=a

print(*ans)

Solution (Python):



import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7

n,k,l = map(int,input().split())
par1 = [i for i in range(n)]
par2 = [i for i in range(n)]

rank1 = [0]*(n)
rank2 = [0]*(n)

def find(x,i):
    if i == 1:
        if par1[x] == x:
            return x
        else:
            par1[x] = find(par1[x],i)
            return par1[x]
    else:
        if par2[x] == x:
            return x
        else:
            par2[x] = find(par2[x],i)
            return par2[x]

def union(x,y,i):
    x = find(x,i)
    y = find(y,i)
    if i == 1:
        if rank1[x] < rank1[y]:
            par1[x] = y
        else:
            par1[y] = x
            if rank1[x] == rank1[y]:
                rank1[x] += 1
    else:
        if rank2[x] < rank2[y]:
            par2[x] = y
        else:
            par2[y] = x
            if rank2[x] == rank2[y]:
                rank2[x] += 1

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

f = defaultdict(lambda : 0)
for i in range(n):
    x = (find(i,1),find(i,2))
    f[x] += 1
    
ans = []
for i in range(n):
    x = (find(i,1),find(i,2))
    ans.append(f[x])
print(*ans)

Solution (Python):
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial



def union_r(node):
    global road_union
    if road_union[node] != node:
        road_union[node] = union_r(road_union[node])
    return road_union[node]

def union_t(node):
    global train_union
    if train_union[node] != node:
        train_union[node] = union_t(train_union[node])
    return train_union[node]


road_union, train_union = [], []


def main():
    node_num, road_num, train_num = map(int, input().split())

    global road_union
    road_union = [i for i in range(node_num + 1)]
    for i in range(road_num):
        a, b = map(int, input().split())
        parent_a = union_r(a)
        parent_b = union_r(b)
        road_union[min(parent_a, parent_b)] = max(parent_a, parent_b)
        

    global train_union
    train_union = [i for i in range(node_num + 1)]
    for i in range(train_num):
        a, b = map(int, input().split())
        parent_a = union_t(a)
        parent_b = union_t(b)
        train_union[min(parent_a, parent_b)] = max(parent_a, parent_b)

    

    ryouhou = [0 for i in range(node_num + 1)]
    for i in range(1, node_num + 1):
        parent_r = union_r(i)
        parent_t = union_t(i)
        ryouhou[i] = (parent_r, parent_t)

    

    count_d = Counter(ryouhou)

    for i in range(1, node_num + 1):
        now_flg = ryouhou[i]
        print(count_d[now_flg], end=' ')
    print()





if __name__ == '__main__':
    main()

Solution (Python):
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)

from math import factorial



def union_r(node):
    global road_union
    if road_union[node] != node:
        road_union[node] = union_r(road_union[node])
    return road_union[node]

def union_t(node):
    global train_union
    if train_union[node] != node:
        train_union[node] = union_t(train_union[node])
    return train_union[node]


road_union, train_union = [], []


def main():
    node_num, road_num, train_num = map(int, input().split())

    global road_union
    road_union = [i for i in range(node_num + 1)]
    for i in range(road_num):
        a, b = map(int, input().split())
        parent_a = union_r(a)
        parent_b = union_r(b)
        road_union[min(parent_a, parent_b)] = max(parent_a, parent_b)
        

    global train_union
    train_union = [i for i in range(node_num + 1)]
    for i in range(train_num):
        a, b = map(int, input().split())
        parent_a = union_t(a)
        parent_b = union_t(b)
        train_union[min(parent_a, parent_b)] = max(parent_a, parent_b)

    

    ryouhou = [0 for i in range(node_num + 1)]
    for i in range(1, node_num + 1):
        parent_r = union_r(i)
        parent_t = union_t(i)
        ryouhou[i] = (parent_r, parent_t)

    

    count_d = Counter(ryouhou)

    for i in range(1, node_num + 1):
        now_flg = ryouhou[i]
        print(count_d[now_flg], end=' ')
    print()





if __name__ == '__main__':
    main()

Solution (Python):

import sys
import math
from collections import defaultdict


sys.setrecursionlimit(10**7)
def input():
  return sys.stdin.readline()[:-1]


mod = 10**9 + 7


def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))



N,K,L = II()
p,q = Line(K)
r,s = Line(L)

class UF(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):
    """
    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 と 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):
    """
    x と y が同じグループか否か
    """
    return self.find(x) == self.find(y)

  def get_size(self, x):
    """
    x が属するグループの要素数
    """
    x = self.find(x)
    return self.size[x]
  
uf1 = UF(N)
uf2 = UF(N)
ans = []

for i in range(K):
  uf1.union(p[i]-1,q[i]-1)

for i in range(L):
  uf2.union(r[i]-1,s[i]-1)

x = []
for i in range(N):
  x.append([uf1.find(i), uf2.find(i)])
y = x[:]
y.sort(key=lambda x:(x[0],x[1]))

from bisect import bisect_left, bisect_right
for i in range(N):
  ans.append(bisect_right(y,x[i])- bisect_left(y,x[i]))

print(*ans)

Solution (Python):

import sys
sys.setrecursionlimit(300000)

class UnionFindTree:

    def __init__(self, N):
        self.par = list(range(N))

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

    def union(self, a, b):
        a_root = self.find_root(a)
        b_root = self.find_root(b)
        self.par[a_root] = b_root
        return


def solve(N: int, K: int, L: int, p: "List[int]", q: "List[int]", r: "List[int]", s: "List[int]"):
    k_uf = UnionFindTree(N)
    l_uf = UnionFindTree(N)
    ret = [1] * N
    for i in range(K):
        k_uf.union(p[i] - 1, q[i] - 1)
    for i in range(L):
        l_uf.union(r[i] - 1, s[i] - 1)

    pars = []
    for i in range(N):
        pars.append((k_uf.find_root(i), l_uf.find_root(i), i))
    pars.sort()
    
    ret = [1] * N
    tmp = set()
    for i in range(1, N):
        if pars[i][0] == pars[i - 1][0] and pars[i][1] == pars[i - 1][1]:
            tmp.add(pars[i][2])
            tmp.add(pars[i - 1][2])
        else:
            cnt = len(tmp)
            for x in tmp:
                ret[x] = cnt
            tmp = set()
    for x in tmp:
        ret[x] = len(tmp)
    print(' '.join([str(r) for r in ret]))
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    K = int(next(tokens))  
    L = int(next(tokens))  
    p = [int()] * (K)  
    q = [int()] * (K)  
    for i in range(K):
        p[i] = int(next(tokens))
        q[i] = int(next(tokens))
    r = [int()] * (L)  
    s = [int()] * (L)  
    for i in range(L):
        r[i] = int(next(tokens))
        s[i] = int(next(tokens))
    solve(N, K, L, p, q, r, s)

if __name__ == '__main__':
    main()

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

class UnionFind:
    def __init__(self,N):
        self.Parent = list(range(N))
    def get_Parent(self,n):
        if self.Parent[n] == n:return n
        p = self.get_Parent(self.Parent[n])
        self.Parent[n] = p
        return p
    def merge(self,x,y):
        x = self.get_Parent(x)
        y = self.get_Parent(y)
        if x!=y: self.Parent[y] = x
        return
    def is_united(self,x,y):
        return self.get_Parent(x)==self.get_Parent(y)

N,K,L = map(int,input().split())
PQ = [list(map(int,input().split())) for _ in [0]*K]
RS = [list(map(int,input().split())) for _ in [0]*L]

T1 = UnionFind(N)
T2 = UnionFind(N)
for p,q in PQ:
    p-=1;q-=1
    T1.merge(p,q)
for r,s in RS:
    r-=1;s-=1
    T2.merge(r,s)
P = {}
for i in range(N):
    p = (T1.get_Parent(i),T2.get_Parent(i))
    if not p in P:P[p] = []
    P[p].append(i)

ans = [0]*N
for v in P.values():
    s = len(v)
    for i in v:
        ans[i] = s
print(*ans)

Solution (Python):
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.children = []
        self.size = 1
    
class UF:
    def __init__(self, size):
        self.n = size
        self.parents = [i for i in range(self.n+1)]
        self.sizes = [1] * (self.n+1)
        self.nodes = [None]
        for i in range(1, self.n+1):
            self.nodes.append(Node(i))
        

    def get_parent(self, x):
        while x.parent != None:
            x = x.parent
        return x

    def union(self, x, y):
        x = self.nodes[x]
        y = self.nodes[y]
        xp = self.get_parent(x)
        yp = self.get_parent(y)
        if xp == yp and xp is not None and yp is not None:
            return
        if xp.size >= yp.size:
            xp.children.append(yp)
            xp.size += yp.size
            self.sink(xp, yp)
        else:
            yp.children.append(xp)
            yp.size += xp.size
            self.sink(yp, xp)

    def sink(self, xp, yp):
        yp.parent = xp
        self.parents[yp.key] = xp.key
        yp.size = xp.size
        for child in yp.children:
            self.sink(xp, child)
            
from collections import defaultdict
n, k, l = map(int, raw_input().split())
uf1 = UF(n)
for i in range(k):
    p, q = map(int, raw_input().split())
    uf1.union(p, q)
uf2 = UF(n)
for i in range(l):
    r, s = map(int, raw_input().split())
    uf2.union(r, s)
p1 = uf1.parents
p2 = uf2.parents
dic = defaultdict(int)
for i in range(1, n+1):
    key = (p1[i], p2[i])
    dic[key] += 1
res_arr = []
for i in range(1, n+1):
    if uf1.nodes[i].size == 1 or uf2.nodes[i].size == 1:
        res_arr.append(1)
    else:
        key = (p1[i], p2[i])
        res_arr.append(dic[key])
print " ".join(map(str, res_arr))

Solution (Python):
class Tree():
  def __init__(s, n):
    s.L = [-1] * n
  def root(s, x):
    if s.L[x] < 0:
      return x, -s.L[x]
    a, b = s.root(s.L[x])
    s.L[x] = a
    return a, b
  def merge(s, a, b):
    ra, sa = s.root(a)
    rb, sb = s.root(b)
    if ra != rb:
      if sa < sb:
        s.L[ra] = rb
        s.L[rb] -= sa
      else:
        s.L[rb] = ra
        s.L[ra] -= sb
      return True
    return False


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

R = Tree(N)
T = Tree(N)

for a, b in pq:
  a -= 1
  b -= 1
  R.merge(a, b)

for a, b in rs:
  a -= 1
  b -= 1
  T.merge(a, b)

RL = [0] * N
for i in range(N):
  RL[i] = R.root(i)[0]

TL = [0] * N
for i in range(N):
  TL[i] = T.root(i)[0]

D = {}
for i in range(N):
  if RL[i] not in D:
    D[RL[i]] = {}
    D[RL[i]][TL[i]] = 1
  else:
    if TL[i] not in D[RL[i]]:
      D[RL[i]][TL[i]] = 1
    else:
      D[RL[i]][TL[i]] += 1

for i in range(N):
  print(D[RL[i]][TL[i]], end = " ")

Solution (Python):


from collections import Counter


class unionfind():
    def __init__(self,n):
        self.par=list(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 is_same(self,x,y):
        return self.find(x)==self.find(y)
    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


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.unite(p,q)

for i in range(l):
    r,s=map(int,input().split())
    uf2.unite(r,s)

res=[]

for i in range(n+1):
    tmp=(uf1.find(i),uf2.find(i))
    res.append(tmp)
c=Counter(res)
ans=[]
for i in range(n+1):
    ans.append(c[res[i]])
print(*ans[1:])

Solution (Python):




import sys
from collections import Counter
input=sys.stdin.readline
sys.setrecursionlimit(10**9)

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


n,k,l=map(int,input().split())
res=[1]*(n+1)
uf1=union_find(n)
for i in range(k):
    p,q=map(int,input().split())
    uf1.unite(p,q)

uf2=union_find(n)
for i in range(l):
    r,s=map(int,input().split())
    uf2.unite(r,s)

res=[]
for i in range(n+1):
    res.append((uf1.find(i),uf2.find(i)))
c=Counter(res)

ans=[]

for i in range(n+1):
    ans.append(c[res[i]])
print(*ans[1:])

Solution (Python):
from collections import Counter
import sys
input = sys.stdin.readline

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

vec1, vec2 = [[] for _ in range(N)], [[] for _ in range(N)]

for _ in range(K) :
    p, q = map(int, input().split())
    vec1[p-1].append(q-1)
    vec1[q-1].append(p-1)
for _ in range(L) :
    r, s = map(int, input().split())
    vec2[r-1].append(s-1)
    vec2[s-1].append(r-1)

def bfs(v) :
    visited = [-1] * N
    n = 0
    for i in range(N) :
        if visited[i] < 0 :
            queue = [i]
            visited[i] = n
            j = 0
            while j < len(queue) :
                cur = queue[j]
                for nex in v[cur] :
                    if visited[nex] < 0 :
                        queue.append(nex)
                        visited[nex] = n
                j += 1
            n += 1
            
    return visited
    
visited1 = bfs(vec1)
visited2 = bfs(vec2)
p = [(visited1[i], visited2[i]) for i in range(N)]
c = Counter(p)

print(' '.join([str(c[p[i]]) for i in range(N)]))

Solution (Python):
from collections import defaultdict

class UnionFind():

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


def main():
    N, K, L = map(int, input().split())
    
    uf1 = UnionFind(N)
    uf2 = UnionFind(N)

    
    for _ in range(K):
        p, q = map(int, input().split())
        uf1.unite(p-1, q-1)
    
    
    for _ in range(L):
        r, s = map(int, input().split())
        uf2.unite(r-1, s-1)

    
    
    
    cnts = defaultdict(int)
    for i in range(N):
        pos = (uf1.root(i), uf2.root(i))
        cnts[pos] += 1

    ans = []
    for i in range(N):
        pos = (uf1.root(i), uf2.root(i))
        ans.append(cnts[pos])

    print(*ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline

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

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

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

u1 = UnionFind(N)
for x, y in LA:
    u1.unite(x, y)
    
u2 = UnionFind(N)
for x, y in LB:
    u2.unite(x, y)

result = {}
for i in range(N):
    a = u1.get_root(i)
    b = u2.get_root(i)
    
    if result.get((a, b)) == None:
        result[(a, b)] = 0
    result[(a, b)] += 1
    
for i in range(N):
    a = u1.get_root(i)
    b = u2.get_root(i)
    
    print(result[(a, b)], end = "")
    if i != N - 1:
        print(" ", end = "")
    else:
        print()

Solution (Python):
n, k, l = map(int, input().split())
from collections import defaultdict

class UnionFind( ):
    def __init__(self, N):
        self.rank = [0] * N
        self.par = [i for i 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 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[y] = x
        else:
            self.par[x] = y
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

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


uf1 = UnionFind(n)
uf2 = UnionFind(n)

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


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

pair = defaultdict(int)
for i in range(n):
    a = uf1.find(i)
    b = uf2.find(i)
    pair[(a, b)] += 1

ans = []
for i in range(n):
    ans.append(pair[(uf1.find(i), uf2.find(i))])

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

Solution (Python):
from collections import Counter

class Union_Find:

    def __init__(self, n):
        self.n = n
        self.par = [i for i in range(n)]
        self.height = [0 for i in range(n)]
        self.size = [1 for i 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 getsize(self, x):
        return self.size[self.find(x)]

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

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

N, K, L = map(int, input().split())
uf0 = Union_Find(N+1)
for i in range(K):
    x, y = map(int, input().split())
    uf0.union(x, y)
uf1 = Union_Find(N+1)
for i in range(L):
    x, y = map(int, input().split())
    uf1.union(x, y)
types = [None] * (N+1)
for i in range(1, N+1):
    types[i] = (uf0.find(i), uf1.find(i))
C = Counter(types)
ans = [None] * (N+1)
for i in range(1, N+1):
    ans[i] = C[types[i]]
print(*ans[1:])

Solution (Python):
class UnionFind():
  def __init__(self,n):
    self.n=n
    self.root=[-1]*(n+1)
    self.rank=[0]*(n+1)
  def FindRoot(self,x):
    if self.root[x]<0:
      return x
    else:
      self.root[x]=self.FindRoot(self.root[x])
      return self.root[x]
  def Unite(self,x,y):
    x=self.FindRoot(x)
    y=self.FindRoot(y)
    if x==y:
      return
    else:
      if self.rank[x]>self.rank[y]:
        self.root[x]+=self.root[y]
        self.root[y]=x
      elif self.rank[x]<=self.rank[y]:
        self.root[y]+=self.root[x]
        self.root[x]=y
        if self.rank[x]==self.rank[y]:
          self.rank[y]+=1
  def isSameGroup(self,x,y):
    return self.FindRoot(x)==self.FindRoot(y)
  def Count(self,x):
    return -self.root[self.FindRoot(x)]
  
n,k,l=map(int,input().split())
t1=UnionFind(n)
t2=UnionFind(n)
for _ in range(k):
  a,b=map(int,input().split())
  t1.Unite(a,b)
for _ in range(l):
  a,b=map(int,input().split())
  t2.Unite(a,b)
dic={}
for i in range(1,n+1):
  pos=(t1.FindRoot(i),t2.FindRoot(i))
  if pos not in dic:
    dic[pos]=1
  else:
    dic[pos]+=1
ans=[]
for i in range(1,n+1):
  pos=(t1.FindRoot(i),t2.FindRoot(i))
  ans.append(dic[pos])
print(*ans)

Solution (Python):
from collections import Counter
N, K, L = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(K)]
Y = [list(map(int, input().split())) for _ in range(L)]

class UnionFind:
    def __init__(self, n):
        self.par = list(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 x == y:
            return
        
        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)
    
    def __repr__(self):
        return ', '.join(str(x) for x in self.par)

t1 = UnionFind(N)
t2 = UnionFind(N)

for p, q in X:
    t1.unite(p - 1, q - 1)
    
for r, s in Y:
    t2.unite(r - 1, s - 1)

connect = [(t1.find(i), t2.find(i)) for i in range(N)]
ctr = Counter(connect)
print(*[ctr[key] for key in connect])

Solution (Python):
import os
import sys
from collections import defaultdict

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18

N, K, L = list(map(int, sys.stdin.readline().split()))
P, Q = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(K)]))
R, S = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(L)]))


class UnionFind:
    def __init__(self, size=None, nodes=None):
        """
        size か nodes どっちか指定。
        nodes は set、size は list を使う。
        set の最悪計算量は O(N) なので size 指定のほうが若干速い
        :param int size:
        :param collections.Iterable nodes:
        """
        assert size is not None or nodes is not None
        if size is not None:
            self._parents = [i for i in range(size)]
            self._ranks = [0 for _ in range(size)]
            self._sizes = [1 for _ in range(size)]
        else:
            self._parents = {k: k for k in nodes}
            self._ranks = {k: 0 for k in nodes}
            self._sizes = {k: 1 for k in nodes}

    def unite(self, x, y):
        """
        x が属する木と y が属する木を併合
        :param x:
        :param y:
        :return:
        """
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return

        
        if self._ranks[x] > self._ranks[y]:
            
            self._parents[y] = x
            self._sizes[x] += self._sizes[y]
        else:
            
            self._parents[x] = y
            self._sizes[y] += self._sizes[x]
            if self._ranks[x] == self._ranks[y]:
                self._ranks[y] += 1

    def find(self, x):
        """
        x が属する木の root
        :param x:
        :return:
        """
        if self._parents[x] == x:
            return x
        self._parents[x] = self.find(self._parents[x])
        return self._parents[x]

    def size(self, x):
        """
        x が属する木のノード数
        :param x:
        :return:
        """
        return self._sizes[self.find(x)]


uf1 = UnionFind(size=N + 1)
for p, q in zip(P, Q):
    uf1.unite(p, q)
uf2 = UnionFind(size=N + 1)
for r, s in zip(R, S):
    uf2.unite(r, s)

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

ans = []
for i in range(1, N + 1):
    ans.append(counts[(uf1.find(i), uf2.find(i))])
print(' '.join(map(str, ans)))

Solution (Python):
from collections import defaultdict
class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]

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

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

        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

N,K,L = map(int,input().split())
u1 = UnionFind(N)
u2 = UnionFind(N)
for _ in range(K):
    p,q = map(int,input().split())
    u1.union(p-1,q-1)
for _ in range(L):
    r,s = map(int,input().split())
    u2.union(r-1,s-1)

d = defaultdict(lambda:0)
for i in range(N):
    d[(u1.find(i),u2.find(i))] += 1

ans = []
for i in range(N):
    ans.append(str(d[(u1.find(i),u2.find(i))]))

ans = ' '.join(ans)
print(ans)

Solution (Python):
class UnionFind():
    def __init__(self, N):
        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]:
                self.rank[x] += 1
            elif self.rank[x] < self.rank[y]:
                x, y = y, x
            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]

from collections import defaultdict

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

for i in range(N):
    print(c[(uf1.find(i), uf2.find(i))], end = ' ', )

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

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

    def root(self, A):
        if self.parent[A] == A:
            return A
        self.parent[A] = self.root(self.parent[A]) 
        return self.parent[A]

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

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




ans = dict()
key_list = []
for i in range(N): 
    root1 = uni1.root(i) 
    root2 = uni2.root(i)
    key = str(root1) + '_' + str(root2) 
    key_list.append(key) 
    if key in ans.keys(): 
        ans[key] += 1
    else:
        ans[key] = 1
    
for i in range(N):
    print (ans[key_list[i]], end = ' ') 
print ()













print ()