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:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict

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

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

    def unite(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x != y:
            self.parent[x] = y

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

N, K, L = map(int, input().split())
un1 = UnionFind(N)
for i in range(K):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    un1.unite(p, q)
un2 = UnionFind(N)
for i in range(L):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    un2.unite(r, s)
dic = defaultdict(int)
for i in range(N):
    a, b = un1.root(i), un2.root(i)
    k = str(a)+":"+str(b)
    dic[k] += 1

ans = [0]*N
for i in range(N):
    a, b = un1.root(i), un2.root(i)
    k = str(a)+":"+str(b)
    ans[i] = dic[k]
print(*ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict

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

# Group1
G1 = [[] for i in range(N)]
for i in range(K):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    G1[p].append(q)
    G1[q].append(p)
gids = [0]*N
done = [False]*N
def dfs1(i, gid):
    gids[i] = gid
    done[i] = True
    for nex in G1[i]:
        if done[nex]: continue
        dfs1(nex, gid)
gid = 0
for i in range(N):
    if not done[i]:
        dfs1(i, gid)
        gid += 1

# Group2
G = [[] for i in range(N)]
for i in range(L):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    G[r].append(s)
    G[s].append(r)
done = [False]*N
D = []
gids2 = [0]*N
def dfs(i, gid):
    D[gid][gids[i]] += 1
    done[i] = True
    gids2[i] = gid
    for nex in G[i]:
        if done[nex]: continue
        dfs(nex, gid)
gid = 0
for i in range(N):
    if not done[i]:
        D.append(defaultdict(int))
        dfs(i, gid)
        gid += 1

# answer
ans = [0]*N
for i in range(N):
    ans[i] = D[gids2[i]][gids[i]]
print(*ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict

N, K, L = map(int, input().split())
G1 = [[] for i in range(N)]
for i in range(K):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    G1[p].append(q)
    G1[q].append(p)
gids = [0]*N
done = [False]*N
def dfs1(i, gid):
    gids[i] = gid
    done[i] = True
    for nex in G1[i]:
        if done[nex]: continue
        dfs1(nex, gid)
gid = 0
for i in range(N):
    if not done[i]:
        dfs1(i, gid)
        gid += 1

G = [[] for i in range(N)]
for i in range(L):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    G[r].append(s)
    G[s].append(r)
done = [False]*N
D = []
gid = 0
def dfs(i, gid):
    D[gid][gids[i]] += 1
    done[i] = True
    for nex in G[i]:
        if done[nex]: continue
        dfs(nex, gid)
for i in range(N):
    if not done[i]:
        D.append(defaultdict(int))
        dfs(i, gid)
        gid += 1
ans = [0]*N
done = [False]*N
gid = 0
def dfs2(i, gid):
    done[i] = True
    ans[i] = D[gid][gids[i]]
    for nex in G[i]:
        if done[nex]: continue
        dfs2(nex, gid)
for i in range(N):
    if not done[i]:
        dfs2(i, gid)
        gid += 1
print(*ans)

Submission status: Accepted

Solution code:
from collections import Counter


class UnionFind:
    def __init__(self, node):
        self.parent = [-1 for _ in range(node)]
        self.node = node

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

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

    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if root_x == root_y:
            return
        if self.parent[root_x] > self.parent[root_y]:
            root_x, root_y = root_y, root_x
        self.parent[root_x] += self.parent[root_y]
        self.parent[root_y] = root_x

    def get_size(self, x):
        return -self.parent[self.find(x)]

    def members(self, x, is_set=False):
        root = self.find(x)
        res = [i for i in range(self.node) if self.find(i) == root]
        if is_set:
            return set(res)
        return res

    def all_root(self):
        return [idx for idx, val in enumerate(self.parent) if val < 0]


def main():
    cities, roads, railroads = map(int, input().split())
    uf_road = UnionFind(cities)
    uf_train = UnionFind(cities)
    for _ in range(roads):
        p, q = map(lambda x: int(x) - 1, input().split())
        uf_road.union(p, q)
    for _ in range(railroads):
        r, s = map(lambda x: int(x) - 1, input().split())
        uf_train.union(r, s)
    each_pair = []
    for i in range(cities):
        each_pair.append(tuple([uf_road.find(i), uf_train.find(i)]))
    pair_count = dict(Counter(each_pair))
    answer = [pair_count[each_pair[i]] for i in range(cities)]
    print(" ".join(map(str, answer)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#UNIONFIND
class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
 
    def _root(self, x):
        if self.table[x] < 0:
            return x
        else:
            # 経路の圧縮
            self.table[x] = self._root(self.table[x])
            return self.table[x]
 
    def find(self, x, y):
        return self._root(x) == self._root(y)
 
    def union(self, x, y):
        r1 = self._root(x)
        r2 = self._root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
 
 
if __name__ == '__main__':
    n,k,l=map(int,input().split())
    pq=UnionFind(n+1)
    rs=UnionFind(n+1)
    for i in range(k):
        p,q=map(int,input().split())
        pq.union(p,q)
    for i in range(l):
        r,s=map(int,input().split())
        rs.union(r,s)
    sameroot=[]
    for i in range(1,n+1):
        sameroot.append([pq._root(i),rs._root(i),i])
    sameroot.sort()
    sameroot.append([0,0,n+1])
    cnt=[0]*(n+1)
    bx,by=0,0
    samelist=[]
    for x,y,i in sameroot:
        if bx==x and by==y:
            samelist.append(i)
        else:
            k=len(samelist)
            if k>0:
                for j in samelist:
                    cnt[j]=k
            samelist=[i]
            bx,by=x,y
    print(' '.join(map(str,cnt[1:])))

Submission status: Accepted

Solution code:
from collections import Counter

class UnionFind:
    #n個の要素を初期化
    def __init__(self, n):
        self.n = 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]
    
    #xとyの属する集合を併合
    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
    
    #xとyが同じ集合に属するか判定
    def same(self, x, y):
        return self.find(x) == self.find(y)

    #要素xが属するグループに属する要素をリストで返す
    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]


N, K, L = map(int, input().split())
roads = [list(map(int, input().split())) for i in range(K)]
trains = [list(map(int, input().split())) for i in range(L)]

uf_road = UnionFind(N)
uf_train = UnionFind(N)

for road in roads:
    x, y = road
    uf_road.unite(x-1, y-1)

for train in trains:
    x, y = train
    uf_train.unite(x-1, y-1)

pairs = []
for i in range(N):
    pairs.append((uf_road.find(i), uf_train.find(i)))

cnt = Counter(pairs)

ans = [cnt[pair] for pair in pairs]
print(*ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
from collections import defaultdict
def main():
    def find(x):
        if par[x] < 0:
            return x
        else:
            par[x] = find(par[x])
            return par[x]
    def unite(x, y):
        x = find(x)
        y = find(y)
        if x == y:
            return False
        else:
            if par[x] > par[y]:
                x, y = y, x
            par[x] += par[y]
            par[y] = x
            return True
    def members(x):
        root = find(x)
        return [i for i in range(n) if find(i) == root]

    def find2(x):
        if par2[x] < 0:
            return x
        else:
            par2[x] = find2(par2[x])
            return par2[x]
    def unite2(x, y):
        x = find2(x)
        y = find2(y)
        if x == y:
            return False
        else:
            if par2[x] > par2[y]:
                x, y = y, x
            par2[x] += par2[y]
            par2[y] = x
            return True
    def members2(x):
        root2 = find2(x)
        return [i for i in range(n) if find2(i) == root2]

    n, k, l = map(int, input().split())
    par = [-1] * n
    par2 = [-1] * n
    for _ in range(k):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        unite(a, b)
    for _ in range(l):
        c, d = map(int, input().split())
        c -= 1
        d -= 1
        unite2(c, d)

    root_pairs = defaultdict(int)
    for i in range(n):
        root_pairs[find(i), find2(i)] += 1

    for i in range(n):
        print(root_pairs[find(i), find2(i)], end=' ')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter

def road_find(a):
    if Road[a] < 0:
        return a
    else:
        return road_find(Road[a])


def train_find(a):
    if Train[a] < 0:
        return a
    else:
        return train_find(Train[a])


def road_union(a, b):
    ag = road_find(a)
    bg = road_find(b)
    if ag == bg:
        return
    if Road[ag] > Road[bg]:
        ag, bg = bg, ag
    Road[ag] += Road[bg]
    Road[bg] = ag
    return


def train_union(a, b):
    ag = train_find(a)
    bg = train_find(b)
    if ag == bg:
        return
    if Train[ag] > Train[bg]:
        ag, bg = bg, ag
    Train[ag] += Train[bg]
    Train[bg] = ag
    return


N, K, L = map(int, input().split())
Road = [-1] * N
Train = [-1] * N

for road in range(K):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    road_union(p, q)

for train in range(L):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    train_union(p, q)

Ans = []
for i in range(N):
    Ans.append((road_find(i),train_find(i)))

Ans_C = Counter(Ans)

for i in range(N):
    print(Ans_C[(road_find(i),train_find(i))])

Submission status: Accepted

Solution code:
from collections import Counter

class UnionFind():
    # 作りたい要素数nで初期化
    # 使用するインスタンス変数の初期化
    def __init__(self, n):
        self.n = n
        # root[x]<0ならそのノードが根かつその値が木の要素数
        # rootノードでその木の要素数を記録する
        self.root = [-1]*(n+1)
        # 木をくっつける時にアンバランスにならないように調整する
        self.rnk = [0]*(n+1)

    # ノードxのrootノードを見つける
    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):
        # 入力ノードのrootノードを見つける
        x = self.find_root(x)
        y = self.find_root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return
        # 違う木に属していた場合rnkを見てくっつける方を決める
        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
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSame(self, x, y):
        return self.find_root(x) == self.find_root(y)

    # ノードxが属する木のサイズを返す
    def size(self, x):
        return -self.root[self.find_root(x)]
        
n,k,l = map(int,input().split())
fe = UnionFind(n)
bus = UnionFind(n)
for _ in range(k):
    p,q = map(int,input().split())
    fe.unite(p,q)
for _ in range(l):
    r,s = map(int,input().split())
    bus.unite(r,s)
cnt = Counter()
for i in range(1,n+1):
    cnt[fe.find_root(i),bus.find_root(i)] += 1

print(*[cnt[fe.find_root(i),bus.find_root(i)]for i in range(1,n+1)])

Submission status: Accepted

Solution code:
# python 3.4.3
import sys
input = sys.stdin.readline
import numpy as np

# -------------------------------------------------------------
# function
# -------------------------------------------------------------
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 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 check(self, x, y):
        return self.find(x) == self.find(y)

# -------------------------------------------------------------
# main
# -------------------------------------------------------------
N,K,L = map(int,input().split())
PQ = [tuple(map(int,input().split())) for _ in range(K)]
RS = [tuple(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)

# 集計
from collections import defaultdict
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)))

Submission status: Accepted

Solution code:
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]
import collections
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 j in range(L):
  r,s=map(int,input().split())
  uf2.union(r-1,s-1)
list=[]
for i in range(N):
  list.append((uf1.find(i),uf2.find(i)))
count=collections.Counter(list)
for i in range(N):
  ans=count[list[i]]
  if i==N-1:
    print(ans)
  else:
    print(ans,end=' ')

Submission status: Accepted

Solution code:
"""
道路でつながっているやつが鉄道でもつながっているかどうかを調べるにはどうすればいい？
普通に木ごとのサイズを求めておけばいいのか？

道路ネットワークを根ごとにグルーピングする。その中で、さらに鉄道の根ごとにグルーピングする。
でchooseでペア数を求めれば良い。

"""
import math
import sys
sys.setrecursionlimit(200000)
class UnionFind():
    def __init__(self,n):
        self.parents = [i for i in range(n+1)]

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

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

N,K,L = map(int,input().split())
A = UnionFind(N)
B = UnionFind(N)
for i in range(K):
    p,q = map(int,input().split())
    A.union(p,q)

for i in range(L):
    r,s = map(int,input().split())
    B.union(r,s)


group = {}
for i in range(1,N+1):
    roadRoot = A.find(i)
    if roadRoot not in group:
        group[roadRoot] = {}
    railRoot = B.find(i)
    if railRoot not in group[roadRoot]:
        group[roadRoot][railRoot] = []
    group[roadRoot][railRoot].append(i)

ans = [[]for _ in range(N)]
for i in group.items():
    for j in i[1].values():
        for k in j:
            ans[k-1] = str(len(j))

ans = " ".join(ans)
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter
n,k,l=map(int,input().split())
city1=[i for i in range(n)]
city2=[i for i in range(n)]
def root(c,x):
  if x==c[x]:
    return x
  else:
    c[x]=root(c,c[x])
    return c[x]
def union(c,x,y):
  rx=root(c,x)
  ry=root(c,y)
  if rx>ry:
    c[rx]=ry
  else:
    c[ry]=rx
for i in range(k):
  a,b=map(int,input().split())
  union(city1,a-1,b-1)
for i in range(l):
  a,b=map(int,input().split())
  union(city2,a-1,b-1)
r=[]
for i in range(n):
  r.append((root(city1,i),root(city2,i)))
c=Counter(r)
for i in range(n):
  ans=c[r[i]]
  if i==n-1:
    print(ans)
  else:
    print(ans,end=' ')

Submission status: Accepted

Solution code:
from collections import Counter
n,k,l=map(int,input().split())
city1=[i for i in range(n)]
city2=[i for i in range(n)]
def root(c,x):
  if x==c[x]:
    return x
  else:
    return root(c,c[x])
def union(c,x,y):
  rx=root(c,x)
  ry=root(c,y)
  if rx>ry:
    c[rx]=ry
  else:
    c[ry]=rx
for i in range(k):
  a,b=map(int,input().split())
  union(city1,a-1,b-1)
for i in range(l):
  a,b=map(int,input().split())
  union(city2,a-1,b-1)
r=[]
for i in range(n):
  r.append((root(city1,i),root(city2,i)))
c=Counter(r)
for i in range(n):
  ans=c[r[i]]
  if i==n-1:
    print(ans)
  else:
    print(ans,end=' ')

Submission status: Accepted

Solution code:
from collections import defaultdict
 
N, K, L = map(int, input().split())

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

# 道路のUnionFind
uf1 = UnionFind(N)
for i in range(K):
    p, q = map(int, input().split())
    uf1.union(p - 1, q - 1)
 
# 鉄道のUnionFind
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))])

Submission status: Accepted

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

class Unionfind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [1]*n
    
    def root(self, x):
        r = x
        
        while not self.par[r]<0:
            r = self.par[r]
        
        t = x
        
        while t!=r:
            tmp = t
            t = self.par[t]
            self.par[tmp] = r
        
        return r
    
    def unite(self, x, y):
        rx = self.root(x)
        ry = self.root(y)
        
        if rx==ry:
            return
        
        if self.rank[rx]<=self.rank[ry]:
            self.par[ry] += self.par[rx]
            self.par[rx] = ry
            
            if self.rank[rx]==self.rank[ry]:
                self.rank[ry] += 1
        else:
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
    
    def is_same(self, x, y):
        return self.root(x)==self.root(y)
    
    def count(self, x):
        return -self.par[self.root(x)]

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)

d = defaultdict(int)

for i in range(N):
    a = uf1.root(i)
    b = uf2.root(i)
    d[10**6*a+b] += 1
    
ans = []

for i in range(N):
    a = uf1.root(i)
    b = uf2.root(i)
    ans.append(d[10**6*a+b])

print(*ans)

Submission status: Accepted

Solution code:
from collections import defaultdict


class UnionFind:

    def __init__(self, n):
        # * Access m-th node by index `m`, not `m - 1`.
        self.parents = [i for i in range(n + 1)]
        self.ranks = [0 for _ in range(n + 1)]

    def find_root(self, node):
        parent_node = self.parents[node]
        if parent_node == node:
            return node
        else:
            root_node = self.find_root(parent_node)
            self.parents[node] = root_node  # reduction
            return root_node

    def union(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        if one_root == other_root:
            return
        if self.ranks[one_root] < self.ranks[other_root]:
            self.parents[one_root] = other_root
        else:
            self.parents[other_root] = one_root
            if self.ranks[one_root] == self.ranks[other_root]:
                self.ranks[one_root] += 1

    def is_same_group(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        return one_root == other_root


def main():
    N, K, L = list(map(int, input().split(' ')))
    road_tree = UnionFind(N)
    for _ in range(K):
        p, q = list(map(int, input().split(' ')))
        road_tree.union(p, q)
    train_tree = UnionFind(N)
    for _ in range(L):
        r, s = list(map(int, input().split(' ')))
        train_tree.union(r, s)
    # Calculate groups
    group_count = defaultdict(int)
    group_list = list()
    for node in range(1, N + 1):
        group = (road_tree.find_root(node), train_tree.find_root(node))
        group_count[group] += 1
        group_list.append(group)
    answer = ' '.join(list(map(
        lambda g: str(group_count[g]),
        group_list
    )))
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

    def find(self, x):  #要素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が属するグループと要素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):   #要素xと要素yが同じグループかどうか
        return self.find(x) == self.find(y)

    def members(self, x):   #要素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())

uf = UnionFind(n)

p, q = [0] * k, [0] * k
for i in range(k):
    pp, qq = map(int, input().split())
    p[i] = pp - 1 
    q[i] = qq - 1
    uf.union(pp - 1, qq - 1)

uuff = UnionFind(n)
r, s = [0] * l, [0] * l
for i in range(l):
    rr, ss = map(int, input().split())
    r[i] = rr - 1
    s[i] = ss - 1
    uuff.union(rr - 1, ss - 1)
dic = defaultdict(int)
for i in range(n):
    dic[(uf.find(i), uuff.find(i))] += 1

ans = []
for i in range(n):
    ans.append(dic[uf.find(i), uuff.find(i)])

for i in ans:
    print(i,end=" ")

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict


def input():
    return sys.stdin.readline().strip()


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

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            self.parent[x] = self.find(self.parent[x])
            return self.parent[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.parent[y] = x
            self.size[x] += self.size[y]
        else:
            self.parent[x] = y
            self.size[y] += self.size[x]
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

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

    def get_parent_list(self):
        return [i for i in range(self.n_nodes) if self.find(i) == i]

    def get_n_groups(self):
        return len(self.get_parent_list())

    def get_members(self, x):
        parent = self.find(x)
        return [i for i in range(self.n_nodes) if self.find(i) == parent]

    def get_members_dict(self):
        return {par: self.get_members(par) for par in self.get_parent_list()}


def main():
    N, K, L = map(int, input().split())
    Tree_road = UnionFind(N)
    Tree_train = UnionFind(N)
    for _ in range(K):
        p, q = map(int, input().split())
        Tree_road.unite(p - 1, q - 1)
    for _ in range(L):
        p, q = map(int, input().split())
        Tree_train.unite(p - 1, q - 1)
    DD = defaultdict(int)
    for i in range(N):
        DD[(Tree_road.find(i), Tree_train.find(i))] += 1
    answer = []
    for i in range(N):
        answer.append(DD[(Tree_road.find(i), Tree_train.find(i))])

    print(*answer, sep=" ")


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


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

    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 unite(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 get_size(self, x):
        return -self.parents[self.find(x)]

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

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

    def get_members(self, x):
        parent = self.find(x)
        return [i for i in range(self.n_nodes) if self.find(i) == parent]

    def get_members_dict(self):
        return {par: self.get_members(par) for par in self.get_parent_list()}


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

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

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

    d = {}
    for i in range(N):
        p1 = tree_road.find(i)
        p2 = tree_subway.find(i)
        if (p1, p2) not in d:
            d[(p1, p2)] = 1
        else:
            d[(p1, p2)] += 1

    for i in range(N):
        p1 = tree_road.find(i)
        p2 = tree_subway.find(i)
        print(d[(p1, p2)], end=" ")


if __name__ == "__main__":
    main()