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:
n, k, l = map(int, input().split())


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

    def root(self, x):
        if(self.tree[x] == x):
            return x
        self.tree[x] = self.root(self.tree[x])
        return self.tree[x]  # 経路圧縮

    def same(self, x, y):  # xとyが同じ木に属するか
        return self.root(x) == self.root(y)

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


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

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

#table = [[0]*n for _ in range(n)]
table = dict()

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

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


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

Submission status: Accepted

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

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

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

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

Submission status: Accepted

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

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

N, K, L = MAP()
pq = [LIST() for _ in range(K)]
rs = [LIST() for _ in range(L)]

class UnionFind:
   def __init__(self, n):
       self.par = [i for i in range(n+1)]
       self.rank = [0] * (n+1)
   # 検索
   def find(self, x):
       if self.par[x] == x:
           return x
       else:
           self.par[x] = self.find(self.par[x])
           return self.par[x]
   # 併合
   def union(self, x, y):
       x = self.find(x)
       y = self.find(y)
       if self.rank[x] < self.rank[y]:
           self.par[x] = y
       else:
           self.par[y] = x
           if self.rank[x] == self.rank[y]:
               self.rank[x] += 1
   # 同じ集合に属するか判定
   def same_check(self, x, y):
       return self.find(x) == self.find(y)

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

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

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

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

Submission status: Accepted

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

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

N, K, L = MAP()
pq = [LIST() for _ in range(K)]
rs = [LIST() for _ in range(L)]

class UnionFind:
   def __init__(self, n):
       self.par = [i for i in range(n+1)]
       self.rank = [0] * (n+1)
   # 検索
   def find(self, x):
       if self.par[x] == x:
           return x
       else:
           self.par[x] = self.find(self.par[x])
           return self.par[x]
   # 併合
   def union(self, x, y):
       x = self.find(x)
       y = self.find(y)
       if self.rank[x] < self.rank[y]:
           self.par[x] = y
       else:
           self.par[y] = x
           if self.rank[x] == self.rank[y]:
               self.rank[x] += 1
   # 同じ集合に属するか判定
   def same_check(self, x, y):
       return self.find(x) == self.find(y)

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

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

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

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

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys

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


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


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

    if x == y:
        return

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


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

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

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

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

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

    print(*cnt)


main()

Submission status: Accepted

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

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

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

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


from collections import deque

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

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

    # print(N, K, L)
    # print(PQ)
    # print(RS)

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

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

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

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

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

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


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

Submission status: Accepted

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

#UnionFind
class UF:
    def __init__(self,n):
        self.n = n
        self.root = [-1]*n #root[x]<0 ならxが根かつその値が木の要素数
        self.rank = [0]*n #木の深さ
    def __del__(self):
        pass
        
    def find(self,x):
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]
            
    def unite(self,x,y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        
        if self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x]+=1
                
    def same(self,x,y):
        return self.find(x) == self.find(y) #bool
    
    def count(self,x):
        return -self.root[self.find(x)]
    
uf1 = UF(N)
for pq in PQ:
    p,q = pq
    uf1.unite(p-1,q-1)
ar = [0]*N
uff1 = [uf1.find(i) for i in range(N)]
for i,u in enumerate(uff1):
    if u < 0:
        ar[i] = i
    else:
        ar[i] = u

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

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

Submission status: Accepted

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

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

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

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

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


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

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

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

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


if __name__ == '__main__':
    abc049_d()

Submission status: Accepted

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

    def __str__(self):
        return '\n'.join('{}: {}'.format(r,self.members(r)) for r in self.roots())
N,K,L = map(int,input().split())
ufK = UnionFind(N)
ufL = UnionFind(N)
ans = [1]*(N)
for i in range(K):
    p,q = map(int,input().split())
    ufK.union(p-1,q-1)
for i in range(L):
    r,s = map(int,input().split())
    ufL.union(r-1,s-1)
from collections import defaultdict
ar=[(ufK.find(i),ufL.find(i)) for i in range(N)]
dic=defaultdict(int)
 
for i in ar:
    dic[i]+=1
ans=[]
for i in range(N):
    ans.append(dic[ar[i]])
print(*ans)

Submission status: Accepted

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

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

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

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

    def isSame(self, x, y):
        return self.par[x] == self.par[y]

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

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

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

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

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

Submission status: Accepted

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

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

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

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

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

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

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

Submission status: Accepted

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

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

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

def unite(x,y): # xとyの属する集合を併合
    x=find(x)
    y=find(y)
    if x==y:return
    if rank[x]<rank[y]:
        par[x]=y
    else:
        par[y]=x
        if rank[x]==rank[y]:
            rank[x]+=1

def same(x,y): # xとyが同じ集合に属するか判定
    return find(x)==find(y)
 
def main():
    n,k,l = inpm()
 
    global par,rank
    par  = [i for i in range(2*n)]
    rank = [-1 for _ in range(2*n)] 
    for _ in range(k):
        p,q = inpm()
        p-=1
        q-=1
        unite(p,q)
    for _ in range(l):
        r,s = inpm()
        r-=1
        s-=1
        unite(r+n,s+n)

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

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

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

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

Submission status: Accepted

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


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

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

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

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

# 道路の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
ans = ""

# 回答を出力
for i in range(N):
    ans += str(c[(uf1.find(i), uf2.find(i))]) + " "
print(ans)

Submission status: Accepted

Solution code:
# python3 (3.4.3)
import sys
input = sys.stdin.readline

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

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

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

# main
from collections import defaultdict
N,K,L = map(int,input().split())
PQ = [list(map(int,input().split())) for _ in range(K)]
RS = [list(map(int,input().split())) for _ in range(L)]

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

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

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

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

Submission status: Accepted

Solution code:
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):
        # 要素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())
################################################################################

def examD():
    N, K, L = LI()
    ans = []
    ufk = UnionFind(N)
    ufl = UnionFind(N)
    for i in range(K):
        p, q = LI()
        ufk.union(p-1,q-1)
    for i in range(L):
        r, s = LI()
        ufl.union(r-1,s-1)
    d = defaultdict(int)
    for i in range(N):
        #各グループの根の組み合わせで記録
        d[(ufk.find(i), ufl.find(i))] += 1
    for i in range(N):
        print(d[(ufk.find(i), ufl.find(i))])


import sys
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
mod = 10**9 + 7
inf = float('inf')

examD()

Submission status: Accepted

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

road_par = []
road_rank = []
rail_par = []
rail_rank = []
c1 = []
c2 = []

def init(par, rank, c, n):
    for i in range(n):
        par.append(i)
        rank.append(0)
        c.append(0)


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


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


N, K, L = map(int, input().split())
init(road_par, road_rank, c1, N)
init(rail_par, rail_rank, c2, N)


for i in range(K):
    f, t = map(int, input().split())
    unite(road_par, road_rank, f-1, t-1)

for i in range(L):
    f,t = map(int, input().split())
    unite(rail_par, rail_rank, f-1, t-1)

for i in range(N):
    c1[find(road_par, i)] += 1
    c2[find(rail_par, i)] += 1

ans = [0 for i in range(N)]

"""
for i in range(N):
    for j in range(N):
        if find(road_par, i) == find(road_par, j) and find(rail_par, i) == find(rail_par, j):
            ans[i] += 1
"""
from collections import defaultdict
ans = defaultdict(int)
for i in range(N):
    ans[(find(road_par, i), find(rail_par, i))] += 1

for i in range(N):
    print(ans[(find(road_par, i), find(rail_par, i))], end=' ')
print('')

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
import sys,bisect,math,itertools,string,queue
from heapq import heappop, heappush
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

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

    #根を返す
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

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

        if x == y:
            return

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

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

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

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

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


n,k,l = inpl()
ro = UnionFind(n)
tr = UnionFind(n)
for i in range(k):
    a,b = inpl()
    ro.union(a-1,b-1)
for i in range(l):
    a,b = inpl()
    tr.union(a-1,b-1)

d = defaultdict(int)
for i in range(n):
    d[(ro.find(i),tr.find(i))] += 1
for i in range(n):
    print(d[(ro.find(i),tr.find(i))])

Submission status: Accepted

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

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

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

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

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

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

def main():
    n,k,l = map(int,input().split())
    Road = [list(map(int,input().split())) for i in range(k)]
    Train = [list(map(int,input().split())) for i in range(l)]

    uf_r = UnionFind(n)
    uf_t = UnionFind(n)

    for i in range(k):
        uf_r.union(Road[i][0]-1,Road[i][1]-1)

    for i in range(l):
        uf_t.union(Train[i][0]-1,Train[i][1]-1)

    Roots_dict = defaultdict(int)
    Roots = []
    for i in range(n):
        Roots.append((uf_r.find(i),uf_t.find(i)))
        Roots_dict[Roots[i]] += 1

    ans = [0]*n

    for i in range(n):
        ans[i] = Roots_dict[Roots[i]]

    print(*ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

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

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

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

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

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

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

def main():
    n,k,l = map(int,input().split())
    Road = [list(map(int,input().split())) for i in range(k)]
    Train = [list(map(int,input().split())) for i in range(l)]

    uf_r = UnionFind(n)
    uf_t = UnionFind(n)

    for i in range(k):
        uf_r.union(Road[i][0]-1,Road[i][1]-1)

    for i in range(l):
        uf_t.union(Train[i][0]-1,Train[i][1]-1)

    Roots_dict = defaultdict(int)
    Roots = []
    for i in range(n):
        Roots.append(str(uf_r.find(i))+' '+str(uf_t.find(i)))
        Roots_dict[Roots[i]] += 1

    ans = [0]*n

    for i in range(n):
        ans[i] = Roots_dict[Roots[i]]

    print(*ans)

if __name__ == '__main__':
    main()