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: Accepted

Solution code:
from collections import defaultdict as dd

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

def uft_root(g, a):
	if g[a] < 0:
		return a
	g[a] = uft_root(g, g[a])
	return g[a]

def uft_size(g, a):
	return -g[uft_root(g, a)]

def uft_merge(g, a, b):
	a, b = uft_root(g, a), uft_root(g, b)
	if a == b:
		return
	size_a, size_b = uft_size(g, a), uft_size(g, b)
	if size_a < size_b:
		a, b = b, a
		size_a, size_b = size_b, size_a
	g[a] -= size_b
	g[b] = a

uft_pq = [-1] * N
uft_rs = [-1] * N

for p, q in PQ:
	p, q = p - 1, q - 1
	uft_merge(uft_pq, p, q)
for r, s in RS:
	r, s = r - 1, s - 1
	uft_merge(uft_rs, r, s)

group = dd(int)
for n in range(N):
	group[(uft_root(uft_pq, n), uft_root(uft_rs, n))] += 1

result = []
for n in range(N):
	result += [group[(uft_root(uft_pq, n), uft_root(uft_rs, n))]]
print(" ".join(map(str, result)))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n)) #親ノード
        self.size = [1]*n #グループの要素数
 
    def root(self, x): #root(x): xの根ノードを返す．
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x 
 
    def merge(self, x, y): #merge(x,y): xのいる組とyのいる組をまとめる
        x, y = self.root(x), self.root(y)
        if x == y: return False
        if self.size[x] < self.size[y]: x,y=y,x #xの要素数が大きいように
        self.size[x] += self.size[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 getsize(self,x): #size(x): xのいるグループの要素数を返す
        return self.size[self.root(x)]


import sys
input = sys.stdin.readline

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

UF1 = UnionFind(n)
for _ in range(k):
    p,q = [int(i)-1 for i in input().split()]
    UF1.merge(p,q)

UF2 = UnionFind(n)
for _ in range(l):
    p,q = [int(i)-1 for i in input().split()]
    UF2.merge(p,q)

a = dict()
for i in range(n):
    r1,r2 = UF1.root(i), UF2.root(i)
    if (r1,r2) not in a:
        a[(r1,r2)] = 1
    else:
        a[(r1,r2)] += 1

print(*[a[(UF1.root(i), UF2.root(i))] for i in range(n)])

Submission status: Accepted

Solution code:
from collections import defaultdict as dd
def find(u,x):
    if u[x]<0:
        return x
    u[x] = find(u,u[x])
    return u[x]

def unite(u,a,b):
    a = find(u,a)
    b = find(u,b)
    if a == b:
        return False
    if u[b] < u[a]:
        a,b = b,a
    u[a] += u[b]
    u[b] = a
    return True
n,k,l = map(int, input().split())
ufr = [-1]*(n+1)
uft = [-1]*(n+1)
for _ in range(k):
    a,b = map(int, input().split())
    unite(ufr,a,b)
for _ in range(l):
    a,b = map(int, input().split())
    unite(uft,a,b)
tot = dd(int)
for i in range(1,n+1):
  tot[(find(ufr,i),find(uft,i))] += 1
print(" ".join([str(tot[(find(ufr,i),find(uft,i))]) for i in range(1,n+1)]))

Submission status: Accepted

Solution code:
from collections import defaultdict

class UnionFind:
    def __init__(self, N):
        # negative value: represents the root of a tree; its absolute value is the size of the tree
        # positive value: the parent's index
        self.vertices = [-1 for _ in range(N)]
        self.rank = [0] * N
        
    def find(self, v):
        if self.vertices[v] < 0: # v is a root
            return v
        else:
            # path compression: reconnect v to the root
            self.vertices[v] = self.find(self.vertices[v])
            return self.vertices[v]
        
    def union(self, u, v):
        s1 = self.find(u) # the root of the tree including vertex u
        s2 = self.find(v) # the root of the tree including vertex v
        
        if s1 == s2: # u and v is in the same tree
            return False
        
        if self.rank[s1] > self.rank[s2]: # the tree including u is taller
            self.vertices[s1] += self.vertices[s2] # update the size of the bigger tree
            self.vertices[s2] = s1
        else: # the tree including v is taller
            self.vertices[s2] += self.vertices[s1] # update the size of the bigger tree
            self.vertices[s1] = s2
            if self.rank[s1] == self.rank[s2]:
                self.rank[s2] += 1
        return True
        
    def is_connected(self, u, v):
        return self.find(u) == self.find(v)
    
    def size(self, v):
        return -self.vertices[self.find(v)]

N, K, L = map(int, input().split())
road = UnionFind(N)
rail = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    road.union(p-1, q-1)
for _ in range(L):
    r, s = map(int, input().split())
    rail.union(r-1, s-1)
comp = defaultdict(int)
tpls = []
for i in range(N):
    t = (road.find(i), rail.find(i))
    comp[t] += 1
    tpls.append(t)
print(*[comp[t] for t in tpls])

Submission status: Accepted

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

e_list1 = [[] for i in range(N)]
e_list2 = [[] for i in range(N)]

for i in range(K):
    p,q = list(map(int,input().split()))
    e_list1[p-1].append(q-1)
    e_list1[q-1].append(p-1)

for i in range(L):
    p,q = list(map(int,input().split()))
    e_list2[p-1].append(q-1)
    e_list2[q-1].append(p-1)


from collections import deque

def BFS(vi,color,color_list,e_list):
    Q = deque([vi])
    color_list[vi]=color
    while len(Q)>0:
        v = Q.pop()
        for v1 in e_list[v]:
            if color_list[v1]==-1:
                color_list[v1]=color
                Q.appendleft(v1)
    return color_list



color_list = [-1 for i in range(N)]
color = 0
for i in range(N):
    if color_list[i]==-1:
        color_list = BFS(i,color,color_list,e_list1)
        color+=1
color_list2 = [-1 for i in range(N)]
color2 = 0
for i in range(N):
    if color_list2[i]==-1:
        color_list2 = BFS(i,color2,color_list2,e_list2)
        color2+=1
M = 1+max(color_list)
color_list = [color_list[i]+M*color_list2[i] for i in range(N)]

from collections import Counter

counter = Counter(color_list)

ans = []

for i in range(N):
    ans.append(counter[color_list[i]])

print(*ans)

Submission status: Accepted

Solution code:
class Union():
  def __init__(me,N):
    me.N = N
    me.up = [-1]*N
    me.down = [ [] for i in range(N) ]
  def union(me,a,b):
    ua = me.up[a] if me.up[a]!=-1 else a
    ub = me.up[b] if me.up[b]!=-1 else b
    if (ua == ub):
      return
    if ( len(me.down[ua]) < len(me.down[ub]) ):
      ub,ua = ua,ub
    for v in me.down[ub]:
      me.up[v] = ua
    me.down[ua].extend( me.down[ub] )
    me.down[ub] = []
    me.up[ub] = ua
    me.down[ua].append( ub )

N,K,L = [ int(it) for it in input().split() ]
uk = Union(N)
for a,b in [ [int(it)-1 for it in input().split()] for i in range(K) ]:
  uk.union(a,b)

ul = Union(N)
for a,b in [ [int(it)-1 for it in input().split()] for i in range(L) ]:
  ul.union(a,b)

pr = [0]*N
for i in range(N):
  ua = uk.up[i] if uk.up[i]!=-1 else i
  ub = ul.up[i] if ul.up[i]!=-1 else i
  pr[i] = (ua*N+ub,i)
pr.sort(key = lambda x:x[0])

li = [0]*N
de = pr[0][0]
s = [pr[0][1]]
for i in range(1,N):
  if (de!=pr[i][0]):
    for v in s:
      li[v] = len(s)
    s=[pr[i][1]]
    de = pr[i][0]
  else:
    s.append(pr[i][1])
for v in s:
  li[v] = len(s)

print ( " ".join( [ str(it) for it in li ]) )

Submission status: Accepted

Solution code:
N,K,L=map(int,input().split())
def search(i,root):
    if root[i]>=0:
        root[i]=search(root[i],root)
        return root[i]
    return i
def UF(N,M):
    root=[-1]*N
    for i in range(M):
        u,v=map(int,input().split())
        u-=1
        v-=1
        ru=search(u,root)
        rv=search(v,root)
        if ru==rv:
            continue
        elif root[ru]<=root[rv]:
            root[rv]+=root[ru]
            root[ru]=rv
        else:
            root[ru]+=root[rv]
            root[rv]=ru
    return [search(i,root) for i in range(N)]
road=UF(N,K)
metro=UF(N,L)
from collections import defaultdict
cnt=defaultdict(int)
ROOT=[(i,j) for i,j in zip(road,metro)]
for r in ROOT:
    cnt[r]+=1
for i in range(N):
    print(cnt[ROOT[i]])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


class UnionFind(object):
    __slots__ = ["nodes"]

    def __init__(self, n: int):
        self.nodes = [-1]*n # 親: -(属するノード数), それ以外: (親ノードindex)

    def find(self, x: int) -> int:
        if self.nodes[x] < 0:
            return x
        else:
            self.nodes[x] = self.find(self.nodes[x]) # compression
            return self.nodes[x]

    def has_same_root(self, x, y) -> bool:
        return self.find(x) == self.find(y)
    
    def size(self, x) -> int:
        return -self.nodes[self.find(x)]

    def unite(self, x: int, y: int) -> None:
        if self.has_same_root(x, y):
            return

        root_x, root_y = self.find(x), self.find(y)
        if self.nodes[root_x] < self.nodes[root_y]:
            bigroot, smallroot = (root_x, root_y)
        else: 
            bigroot, smallroot = (root_y, root_x)
        self.nodes[bigroot] += self.nodes[smallroot]
        self.nodes[smallroot] = bigroot


def solve(N: int, K: int, L: int, p: "List[int]", q: "List[int]", r: "List[int]", s: "List[int]"):
    con_road = UnionFind(N)
    con_rail = UnionFind(N)
    for i in range(K):
        con_road.unite(p[i], q[i])
    for i in range(L):
        con_rail.unite(r[i], s[i])
    
    count = {}
    for i in range(N):
        key = (con_road.find(i), con_rail.find(i))
        count[key] = count.get(key, 0) + 1
    
    print(' '.join(str(count[(con_road.find(i), con_rail.find(i))]) for i in range(N)))
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    L = int(next(tokens))  # type: int
    p = [int()] * (K)  # type: "List[int]" 
    q = [int()] * (K)  # type: "List[int]" 
    for i in range(K):
        p[i] = int(next(tokens))-1
        q[i] = int(next(tokens))-1
    r = [int()] * (L)  # type: "List[int]" 
    s = [int()] * (L)  # type: "List[int]" 
    for i in range(L):
        r[i] = int(next(tokens))-1
        s[i] = int(next(tokens))-1
    solve(N, K, L, p, q, r, s)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,K,L=map(int,input().split())
Road_P=[i for i in range(N+1)]
Road_size=[1 for i in range(N+1)]

def find_road(a):
    if a==Road_P[a]:
        return a
    else:
        return find_road(Road_P[a])
        
def union_road(b,c):
    B=find_road(b)
    C=find_road(c)
    if Road_size[B]>=Road_size[C]:
        Road_P[C]=Road_P[B]
        Road_size[B]+=Road_size[C]
    else:
        Road_P[B]=Road_P[C]
        Road_size[C]+=Road_size[B]

for i in range(K):
    p,q=map(int,input().split())
    if find_road(p)!=find_road(q):
        union_road(p,q)
#print(Road_P)

Rail_P=[i for i in range(N+1)]
Rail_size=[1 for i in range(N+1)]

def find_rail(a):
    if a==Rail_P[a]:
        return a
    else:
        return find_rail(Rail_P[a])
        
def union_rail(b,c):
    B=find_rail(b)
    C=find_rail(c)
    if Rail_size[B]>=Rail_size[C]:
        Rail_P[C]=Rail_P[B]
        Rail_size[B]+=Rail_size[C]
    else:
        Rail_P[B]=Rail_P[C]
        Rail_size[C]+=Rail_size[B]

for i in range(L):
    p,q=map(int,input().split())
    if find_rail(p)!=find_rail(q):
        union_rail(p,q)

#print(Rail_P)

comb={}
for i in range(1,N+1):
    if (find_road(i),find_rail(i)) in comb:
        comb[(find_road(i),find_rail(i))]+=1
    else:
        comb[(find_road(i),find_rail(i))]=1

#print(comb)

for i in range(1,N+1):
    print(comb[(find_road(i),find_rail(i))])

Submission status: Accepted

Solution code:
from collections import*
class UNION_FIND(object):
    def __init__(self,n):
        #親の番号を格納する。親だった場合は-(その集合のサイズ)
        #作るときはParentの値を全て-1にする
        #こうすると全てバラバラになる
        self.parent=[-1 for i in range(n)]
        
    def root(self,x):
        #Aがどのグループに属しているか調べる
        if self.parent[x]<0:
            return x
        else:
            self.parent[x]=self.root(self.parent[x])  #親を再帰で探知 再帰は最後に上のifにひっかかる
            return self.parent[x]
 
    def size(self,x):
        #自分のいるグループの頂点数を調べる
        return -self.parent[self.root(x)]   #親をとってきたい
        
    def union(self,x,y):
        #AとBをくっ付ける
        #AとBを直接つなぐのではなく、root(A)にroot(B)をくっつける
        #print(self.parent)
        x=self.root(x)
        y=self.root(y)
        #print(x,y)
        if x==y:   #すでにくっついてるからくっ付けない
            return False
            
        #大きい方(A)に小さいほう(B)をくっ付けたい
        #大小が逆だったらひっくり返しちゃう。
        if self.size(x)<self.size(y):
            x,y=y,x
        self.parent[x]+=self.parent[y]  #Aのサイズを更新する
        self.parent[y]=x   #Bの親をAに変更する
        return True


n,k,l=map(int,input().split())
u1=UNION_FIND(n)
u2=UNION_FIND(n)
d=defaultdict(int)

for i in range(k):
    a,b=map(int,input().split())
    u1.union(a-1,b-1)
for i in range(l):
    a,b=map(int,input().split())
    u2.union(a-1,b-1)

for i in range(n):
    d[(u1.root(i),u2.root(i))]+=1
print(*[d[(u1.root(i),u2.root(i))]for i in range(n)])

Submission status: Accepted

Solution code:
from collections import*
import sys
input=sys.stdin.readline


class UNION_FIND(object):
    def __init__(self,n):
        #親の番号を格納する。親だった場合は-(その集合のサイズ)
        #作るときはParentの値を全て-1にする
        #こうすると全てバラバラになる
        self.parent=[-1 for i in range(n)]
        
    def root(self,x):
        #Aがどのグループに属しているか調べる
        if self.parent[x]<0:
            return x
        else:
            self.parent[x]=self.root(self.parent[x])  #親を再帰で探知 再帰は最後に上のifにひっかかる
            return self.parent[x]
 
    def size(self,x):
        #自分のいるグループの頂点数を調べる
        return -self.parent[self.root(x)]   #親をとってきたい
        
    def union(self,x,y):
        #AとBをくっ付ける
        #AとBを直接つなぐのではなく、root(A)にroot(B)をくっつける
        #print(self.parent)
        x=self.root(x)
        y=self.root(y)
        #print(x,y)
        if x==y:   #すでにくっついてるからくっ付けない
            return False
            
        #大きい方(A)に小さいほう(B)をくっ付けたい
        #大小が逆だったらひっくり返しちゃう。
        if self.size(x)<self.size(y):
            x,y=y,x
        self.parent[x]+=self.parent[y]  #Aのサイズを更新する
        self.parent[y]=x   #Bの親をAに変更する
        return True
        
n,k,l=map(int,input().split())
u1=UNION_FIND(n)
u2=UNION_FIND(n)
d=defaultdict(int)
for i in range(k):
    p,q=map(int,input().split())
    u1.union(p-1,q-1)
for i in range(l):
    p,q=map(int,input().split())
    u2.union(p-1,q-1)
for i in range(n):
    d[(u1.root(i),u2.root(i))]+=1
print(*[d[(u1.root(i),u2.root(i))]for i in range(n)])

Submission status: Accepted

Solution code:
from collections import defaultdict

class UnionFind:
    def __init__(self, n):
        # 親要素のノード番号を格納　par[x] == x の時そのノードは根
        self.par = [i for i in range(n+1)]
        # 木の高さを格納する（初期状態では0)
        self.rank = [0] * (n+1)
        # 各々の集合の要素数（根が代表して値を持っておく）
        self.count = [1] * (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
            self.count[y] += self.count[x]
            self.count[x] = 0
        else:
            self.par[y] = x
            self.count[x] += self.count[y]
            self.count[y] = 0
            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 size(self,x):
        q = UnionFind.find(self,x)
        return self.count[q]

n, k ,l = map(int,input().split())
road = UnionFind(n)
train = UnionFind(n)

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

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

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

print(*[d[i] for i in a])

Submission status: Accepted

Solution code:
def init(par, n):
    global rank
    par = [i for i in range(n)]
    rank = [0] * n

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

def unite(par, x, y):
    global rank
    x = find(par, x)
    y = find(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

N, K, L = map(int, input().split())
roads = [i for i in range(N)]
rank = [0] * N
for i in range(K):
    p, q = map(int, input().split())
    unite(roads, p - 1, q - 1)
rails = [i for i in range(N)]
rank = [0] * N
for i in range(L):
    p, q = map(int, input().split())
    unite(rails, p - 1, q - 1)
d = {}
for i in range(N):
    d[find(roads, i), find(rails, i)] = d.get((find(roads, i), find(rails, i)), 0) + 1
for i in range(N):
    print(d[find(roads, i), find(rails, i)], end = " ")
print()

Submission status: Accepted

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

ar = [i for i in range(n)]
ah = [0 for _ in range(n)]
br = [i for i in range(n)]
bh = [0 for _ in range(n)]

def root(l, i):
  if l[i] == i:
    return i
  else:
    l[i] = root(l, l[i])
    return l[i]

def union(l, h, i, j):
  ip = root(l, i)
  jp = root(l, j)
  if ip == jp:
    return
  else:
    if h[ip] < h[jp]:
      l[ip] = jp
    elif h[ip] > h[jp]:
      l[jp] = ip
    else:
      if ip < jp:
        l[jp] = ip
        h[ip] += 1
      else:
        l[ip] = jp
        h[jp] += 1

for _ in range(k):
  p, q = map(int, input().split())
  if p < q:
    union(ar, ah, p-1, q-1)
  else:
    union(ar, ah, q-1, p-1)

for _ in range(l):
  r, s = map(int, input().split())
  if r < s:
    union(br, bh, r-1, s-1)
  else:
    union(br, bh, s-1, r-1)

abd = {}
for a, b in zip(ar, br):
  if (root(ar, a), root(br, b)) in abd:
    abd[(root(ar, a), root(br, b))] += 1
  else:
    abd[(root(ar, a), root(br, b))] = 1

for a, b in zip(ar, br):
  print(abd[(root(ar, a), root(br, b))])

Submission status: Accepted

Solution code:
from collections import*
class UnionFind():
    def __init__(self,size):
        self.table=[-1]*size
    def root(self,x):
        while self.table[x]>=0:
            x=self.table[x]
        return x
    def unite(self,x,y):
        s1=self.root(x)
        s2=self.root(y)
        if s1!=s2:
            if self.table[s1]>self.table[s2]:
                s1,s2=s2,s1
            self.table[s1]+=self.table[s2]
            self.table[s2]=s1
        return
    def same(self,x,y):
        return self.root(x)==self.root(y)
    def size(self,x):
        return -self.table[self.root(x)]
input=open(0).readline
n,k,l=map(int,input().split())
u=UnionFind(n)
v=UnionFind(n)
for _ in range(k):
    p,q=map(int,input().split())
    u.unite(p-1,q-1)
for _ in range(l):
    r,s=map(int,input().split())
    v.unite(r-1,s-1)
d=defaultdict(int)
a=[]
for i in range(n):
    t=(u.root(i),v.root(i))
    d[t]+=1
    a.append(t)
print(*[d[i]for i in a])

Submission status: Accepted

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


class UFT:
    def __init__(self, N):
        self.UFdata = [-1] * (N+1)
        self.rank   = [0]  * (N+1)

    def find(self,x):
        UFdata = self.UFdata
        while UFdata[x] != -1:
            x = UFdata[x]
        return x

    def unite(self,x,y):
        UFdata = self.UFdata
        rank = self.rank 
        find = self.find

        x = find(x)
        y = find(y)
        if x != y:
            if rank[x] < rank[y]:
                x,y = y,x
            if rank[x] == rank[y]:
                rank[x] += 1
            UFdata[y] = x       
            

UF1 = UFT(N)
UF2 = UFT(N)
ans = [1] * (N+1)
# MAP= [ [0] * (N+1) for _ in range(N+1)]
import sys
input = sys.stdin.readline
#PQ = [ [int(j) for j in input().split()] for _ in range(K)]
#RS = [ [int(j) for j in input().split()] for _ in range(L)]

for i in range(K):
    p,q = map(int,input().split())
    UF1.unite(p,q)
for i in range(L):
    p,q = map(int,input().split())#RS[i]
    UF2.unite(p, q)
counter=[]
from collections import defaultdict
cntdic =defaultdict(int)
for i in range(1,N+1):
  counter.append(UF1.find(i)+UF2.find(i)*10**6)
  cntdic[counter[-1]]+=1 

ans = [0]*(N+1)
for i in range(1,N+1):
    ans[i] = cntdic[counter[i-1]]

del ans[0]
# print(" ".join( map(lambda x: str(x), connected_num[1:])))
print(" ".join( map(lambda x: str(x), ans)))

Submission status: Accepted

Solution code:
from collections import defaultdict

class UF():
    def __init__(self,n):
        self.l = [-1]*n
    def root(self, a):
        if self.l[a] < 0:
            return a
        else:
            self.l[a] = self.root(self.l[a])
        return self.l[a]
    def unite(self, a, b):
        a, b = self.root(a), self.root(b)
        if a == b:
            return
        if self.l[a] > self.l[b]:
            a, b = b, a
        self.l[a] += self.l[b]
        self.l[b] = a

n,k,l = map(int, input().split())
d = UF(n)
t = UF(n)
for i in range(k):
    r,s = map(int,input().split())
    d.unite(r-1, s-1)
for i in range(l):
    r,s = map(int,input().split())
    t.unite(r-1, s-1)
d_set = defaultdict(set)
t_set = defaultdict(set)
for i in range(n):
    d_set[d.root(i)].add(i)
    t_set[t.root(i)].add(i)

ans = []
cache = {}
for i in range(n):
    rd = d.root(i)
    rt = t.root(i)
    if (rd,rt) in cache:
        ans.append(cache[(rd,rt)])
    else:
        _ = len(d_set[rd] & t_set[rt])
        cache[(rd,rt)] = _
        ans.append(_)
print(*ans)

Submission status: Accepted

Solution code:
# D
class UnionFind:
    """size(int)を指定
    root(x:int)->int:      根を求める
    unite(x,y:int):        要素をグループにまとめる 
    isSame(x,y:int)->bool: 要素同士が同じグループか判定する
    """
    # 分離はできない
    # 始め各要素は別々のグループ  
    def __init__(self, size: int):
        self.par = [-1]*size # 親の番号
        for i in range(size):
            self.par[i] = i  # はじめ すべての頂点が根
    
    def root(self, x: int) -> int:
        """根を求める"""
        if self.par[x] == x: # if root
            return x
        else:
            self.par[x] = self.root(self.par[x]) # 経路圧縮
            return self.par[x]
    
    def isSame(self, x:int, y:int)->bool:
        """x と y が同じ集合に属するか否か"""
        return self.root(x)==self.root(y)
    
    def unite(self, x:int, y:int):
        """x と y の属する集合を併合"""
        x = self.root(x)
        y = self.root(y)
        if x == y: return
        self.par[x] = y
        
# ------------------
N,K,L = map(int, input().split())
uf_k = UnionFind(N)
uf_l = UnionFind(N)
for _ in range(K):
    p,q = map(int, input().split())
    uf_k.unite(p-1, q-1)
for _ in range(L):
    r,s= map(int, input().split())
    uf_l.unite(r-1, s-1)

cnt = dict()
for i in range(N):
    r_k,r_l = uf_k.root(i), uf_l.root(i)
    if (r_k,r_l) in cnt.keys():
        cnt[(r_k,r_l)] += 1
    else:
        cnt[(r_k,r_l)] = 1

ans = []
for i in range(N):
    r_k,r_l = uf_k.root(i), uf_l.root(i)
    ans.append(cnt[(r_k,r_l)])
print(*ans, sep=" ", end="\n")

Submission status: Accepted

Solution code:
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


class UnionFind:
    def __init__(self, size):
        self.parent = [i for i in range(size)]
        self.rank = [0 for _ in range(size)]

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

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

        if self.rank[x] < self.rank[y]:
            self.parent[x] = y
        else:
            self.parent[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 __str__(self):
        ret = "parents\n"
        ret += " ".join(map(str, self.parent))
        ret += '\n'
        ret += " ".join(map(str, self.rank))
        return ret


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


def solve1():
    root = UnionFind(N)
    train = UnionFind(N)

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

    for _ in range(L):
        a, b = map(lambda x: int(x)-1, input().split())
        train.union(a, b)
    ans = [1]*N
    for i in range(N):
        for j in range(N):
            if i == j:
                continue
            else:
                if root.same(i, j) and train.same(i, j):
                    ans[i] += 1
    print(" ".join(map(str, ans)))


def solve2():
    ans = [0]*N
    root = UnionFind(N)
    train = UnionFind(N)
    for _ in range(K):
        a, b = map(lambda x: int(x)-1, input().split())
        root.union(a, b)

    for _ in range(L):
        a, b = map(lambda x: int(x)-1, input().split())
        train.union(a, b)

    d = 10**6
    nums = dict()
    for i in range(N):
        n = root.find(i)+train.find(i)*d
        if n in nums.keys():
            nums[n] = nums[n]+1
        else:
            nums[n] = 1

    for i in range(N):
        ans[i] = nums[root.find(i)+train.find(i)*d]

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


solve2()

Submission status: Accepted

Solution code:
#Union Find
import sys
#木の根を求める
def find(x,par):
    if par[x] == x:
        return x
    else:
        return find(par[x],par)

#xとyの属する集合の併合
def unite(x,y,par,rank):
    x = find(x,par)
    y = find(y,par)
    
    if x != y:
        #xとyの属している集合が異なる時
        if rank[x] < rank[y]:
            par[x] = y
        else:
            par[y] = x
            if rank[x]==rank[y]:
                rank[x] += 1

#xとyが同じ集合に属するかの判定
def same(x,y,par):
    return find(x,par) == find(y,par)
    
input = sys.stdin.readline
n,k,L = map(int,input().split())
rpar = [] #親
tpar = []
rrank = [0]*n#木の深さ
trank= [0]*n

#初期化
for i in range(n):
    #par[i]:i rank[i]:0
    rpar.append(i)
    tpar.append(i)


for i in range(k):
    x,y = map(int,input().split())
    unite(x-1,y-1,rpar,rrank)
for i in range(L):
    x,y = map(int,input().split())
    unite(x-1,y-1,tpar,trank)

num = []
d = {}
for i in range(n):
    num.append(find(i,rpar)+find(i,tpar)*10**6)
    if num[-1] in d:
        d[num[-1]] += 1
    else:
        d[num[-1]] = 1
res = ''
for i in range(n):
    if i != 0:
        res += ' '
    
    res += str(d[num[i]])

print(res)

Submission status: Accepted

Solution code:
#Union Find

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

#xとyの属する集合の併合
def unite(x,y,par,rank):
    x = find(x,par)
    y = find(y,par)
    
    if x != y:
        #xとyの属している集合が異なる時
        if rank[x] < rank[y]:
            par[x] = y
        else:
            par[y] = x
            if rank[x]==rank[y]:
                rank[x] += 1

#xとyが同じ集合に属するかの判定
def same(x,y,par):
    return find(x,par) == find(y,par)
n,k,L = map(int,input().split())
rpar = [] #親
tpar = []
rrank = [0]*n#木の深さ
trank= [0]*n

#初期化
for i in range(n):
    #par[i]:i rank[i]:0
    rpar.append(i)
    tpar.append(i)


for i in range(k):
    x,y = map(int,input().split())
    unite(x-1,y-1,rpar,rrank)
for i in range(L):
    x,y = map(int,input().split())
    unite(x-1,y-1,tpar,trank)

num = []
d = {}
for i in range(n):
    num.append(find(i,rpar)+find(i,tpar)*10**6)
    if num[-1] in d:
        d[num[-1]] += 1
    else:
        d[num[-1]] = 1
res = ''
for i in range(n):
    if i != 0:
        res += ' '
    
    res += str(d[num[i]])

print(res)

Submission status: Accepted

Solution code:
import array
import collections


class UnionFind(object):
    def __init__(self, number_of_nodes):
        # Don't use self.par directly! (call self.root)
        self.par = array.array("L", range(number_of_nodes))
        self.rank = array.array("L", (0 for _ in range(number_of_nodes)))

    def root(self, node):
        if self.par[node] == node:
            return node
        else:
            r = self.root(self.par[node])
            self.par[node] = r
            return r

    def in_the_same_set(self, node1, node2):
        return self.root(node1) == self.root(node2)

    def unite(self, node1, node2):
        x = self.root(node1)
        y = self.root(node2)
        if x == y:
            pass
        elif 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())
roads = [map(int, input().split()) for _ in range(k)]
trains = [map(int, input().split()) for _ in range(l)]

uf1 = UnionFind(n+1)
for p, q in roads:
  uf1.unite(p, q)

uf2 = UnionFind(n+1)
for r, s in trains:
  uf2.unite(r, s)

count = collections.Counter([(uf1.root(i), uf2.root(i)) for i in range(1,n+1)])

print(' '.join([str(count[(uf1.root(i), uf2.root(i))]) for i in range(1,n+1)]))