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:
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.root = [-1] * (n+1)
    self.rank = [0] * (n+1)
  
  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):
    xr = self.find(x)
    yr = self.find(y)
    if xr == yr:
      return
    elif self.rank[xr] < self.rank[yr]:
      self.root[yr] += self.root[xr]
      self.root[xr] = yr
    else:
      self.root[xr] += self.root[yr]
      self.root[yr] = xr
      if self.rank[xr] == self.rank[yr]:
        self.rank[xr] += 1
   
  def same(self, x, y):
    return self.find(x) == self.find(y)
  
  def count(self, x):
    return -self.root[self.find(x)]

N, K, L = map(int, input().split())
roads = UnionFind(N)
for _ in range(K):
  x, y = map(int, input().split())
  roads.unite(x, y)
rails = UnionFind(N)
for _ in range(L):
  x, y = map(int, input().split())
  rails.unite(x, y)
r_dict = {}
for i in range(1, N+1):
  x, y = roads.find(i), rails.find(i)
  if (x, y) in r_dict:
    r_dict[(x, y)] += 1
  else:
    r_dict[(x, y)] = 1
ans = []
for i in range(1, N+1):
  x, y = roads.find(i), rails.find(i)
  ans.append(r_dict[(x, y)])
print(' '.join(map(str, ans)))

Submission status: Accepted

Solution code:
from collections import deque
N, K, L = map(int, input().split())
roads = [[] for _ in range(N)]
rails = [[] for _ in range(N)]
group = [[-1, -1, i] for i in range(N)]
for i in range(K):
    p, q = map(int, input().split())
    roads[p-1].append(q-1)
    roads[q-1].append(p-1)
for i in range(L):
    p, q = map(int, input().split())
    rails[p-1].append(q-1)
    rails[q-1].append(p-1)
def BFS(v0, List, i):
    que = deque([v0])
    while que:
        v = que.pop()
        group[v][i] = v0
        for e in List[v]:
            if group[e][i]<0:
                que.append(e)
for v in range(N):
    if group[v][0]<0:
        BFS(v, roads, 0)
    if group[v][1]<0:
        BFS(v, rails, 1)
group.sort()
ans = [0]*N
cnt = 1
start = 0
for i in range(N-1):
    if group[i][:2] == group[i+1][:2]:
        cnt+=1
    else:
        for j in range(start, i+1):
            c = group[j][2]
            ans[c] = cnt
        cnt = 1
        start = i+1
for j in range(start, N):
    c = group[j][2]
    ans[c] = cnt
print(*ans)

Submission status: Accepted

Solution code:

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




class Union_Find():
	def __init__(self, n):
		self.union = [i for i in range(n)]
		self.level = [0 for i in range(n)]

	def root(self, i, mode=0):
		keiro = [i]
		ans = i
		while ans != self.union[ans]:
			ans = self.union[ans]
			keiro.append(ans)
		if mode == 0:
			return ans
		else:
			return ans, keiro

	def unite(self, i, j):
		root_i, list_i = self.root(i, 1)
		root_j, list_j = self.root(j, 1)
		if root_i != root_j:
			if self.level[root_i] < self.level[root_j]:
				self.level[root_j] = max(self.level[root_i] + 1, self.level[root_j])
				for node in list_i:
					self.union[node] = root_j
			else:
				self.level[root_i] = max(self.level[root_j] + 1, self.level[root_i])
				for node in list_j:
					self.union[node] = root_i

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

UF_road = Union_Find(N)
UF_train = Union_Find(N)
for i in range(K):
	p, q = list(map(int, input().split()))
	p -= 1
	q -= 1
	UF_road.unite(p,q)
for i in range(L):
	p, q = list(map(int, input().split()))
	p -= 1
	q -= 1
	UF_train.unite(p,q)

group = []
for i in range(N):
	group.append([UF_road.root(i), UF_train.root(i), i])
group.append([100000000,0,0])
group.sort()
X = group[0][0:2]
town = [group[0][2]]
number = [-1 for i in range(N)]
for i in range(1, N + 1):
	if X != group[i][0:2]:
		num = len(town)
		for j in town:
			number[j] = num
		town = [group[i][2]]
	else:
		town.append(group[i][2])
	X = group[i][0:2]


def list_print(A):
	length = len(A)
	for i in range(length - 1):
		print(A[i], end="")
		print(" ", end="")
	print(A[N - 1])

list_print(number)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 11:26:39 2019
D - 連結 / Connectivity
実行時間制限: 2 sec / メモリ制限: 256 MB

配点 : 
400 点
@author: justwah
"""
import sys

input = sys.stdin.readline # use this runtime 1523 ms> 1214ms

class UnionFind:
    def __init__(self, n):
        self.rank = [0]*n
        self.parent = [-1]*n
        self.n = n
        
    def root(self, x):
        if self.parent[x] < 0:
            return x
        else:
            self.parent[x] = self.root(self.parent[x])
            return self.parent[x]
        
    def merge(self, a, b):
        a = self.root(a)
        b = self.root(b)
        if a == b:
            return
        if self.rank[a] < self.rank[b]:
            self.parent[a] = b
        else:
            self.parent[b] = a
            if self.rank[a] == self.rank[b]:
                self.rank[a] +=1
                
    def same(self, a, b):
        return self.root(a) == self.roob(b)


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

uf_road = UnionFind(n)
for _ in range(k):
    p, q = map(int, input().split())
    uf_road.merge(p-1, q-1)

uf_rail = UnionFind(n)
for _ in range(l):
    r, s = map(int, input().split())
    uf_rail.merge(r-1, s-1)
    
d = {}
IDs = [0]*n
for i in range(n):
    ID = (uf_road.root(i), uf_rail.root(i))
    IDs[i] = ID
    if ID in d:
        d[ID] += 1
    else:
        d[ID] = 1

ans = []
for i in range(n):
    ans.append(d[IDs[i]])
print(*ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 11:26:39 2019
D - 連結 / Connectivity
実行時間制限: 2 sec / メモリ制限: 256 MB
 
配点 : 
400 点
@author: justwah
"""
from collections import Counter
import sys

input = sys.stdin.readline
 
class UnionFind:
    def __init__(self, N):
        self.rank = [0]*N
        self.parent = [i for i in range(N)]
        self.n = 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 merge(self, a, b):
        a = self.root(a)
        b = self.root(b)
        if a == b:
            return
        if self.rank[a] < self.rank[b]:
            self.parent[a] = b
        else:
            self.parent[b] = a
            if self.rank[a] == self.rank[b]:
                self.rank[a] +=1
                
    def same(self, a, b):
        return self.root(a) == self.roob(b)
 
 
n, k, l = map(int, input().split())
 
uf_road = UnionFind(n)
for _ in range(k):
    p, q = map(int, input().split())
    uf_road.merge(p-1, q-1)

uf_rail = UnionFind(n)
for _ in range(l):
    r, s = map(int, input().split())
    uf_rail.merge(r-1, s-1)
    
ctr = Counter()
for i in range(n):  # make a list to count number of cities that both road and rail-wise are in the same group
    r1 = uf_road.root(i)
    r2 = uf_rail.root(i)
    ctr[(r1,r2)] += 1

ans = []
for i in range(n): # print the group size of that city when looped
    r1 = uf_road.root(i)
    r2 = uf_rail.root(i)
    ans.append(ctr[(r1,r2)])

print(*ans)   # * is for unpack the list

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def Find(x, par):
  if par[x] < 0:
    return x
  else:
    par[x] = Find(par[x], par)
    return par[x]

def Unite(x, y, par, rank):
  x = Find(x, par)
  y = Find(y, par)
  
  if x != y:
    if rank[x] < rank[y]:
      par[x] = y
    else:
      par[y] = x
      if rank[x] == rank[y]:
        rank[x] += 1
    
def Same(x, y, par):
  return Find(x, par) == Find(y, par)
 
n, k, l = map(int, input().split())
rpar = [-1]*n
tpar = [-1]*n
rrank = [0]*n
trank = [0]*n
 
for i in range(k):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, rpar, rrank) 

for i_ in range(l):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, tpar, trank)

d = {}
IDs = [0]*n
for j in range(n):
  ID = Find(j, rpar)+(Find(j, tpar)+1)*10**8
  IDs[j] = ID
  if ID in d:
    d[ID] += 1
  else:
    d[ID] = 1

ans = []
for j in range(n):
    ans.append(d[IDs[j]])
print(*ans)

Submission status: Accepted

Solution code:
def Find(x, par):
  if par[x] < 0:
    return x
  else:
    par[x] = Find(par[x], par)
    return par[x]

def Unite(x, y, par, rank):
  x = Find(x, par)
  y = Find(y, par)
  
  if x != y:
    if rank[x] < rank[y]:
      par[x] = y
    else:
      par[y] = x
      if rank[x] == rank[y]:
        rank[x] += 1
    
def Same(x, y, par):
  return Find(x, par) == Find(y, par)
 
n, k, l = map(int, input().split())
rpar = [-1]*n
tpar = [-1]*n
rrank = [0]*n
trank = [0]*n
 
for i in range(k):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, rpar, rrank) 

for i_ in range(l):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, tpar, trank)

d = {}
IDs = [0]*n
for j in range(n):
  ID = Find(j, rpar)+(Find(j, tpar)+1)*10**8
  IDs[j] = ID
  if ID in d:
    d[ID] += 1
  else:
    d[ID] = 1


ans = ''
for j_ in range(n):
  if j_ != 0:
    ans += ' '
  ans += str(d[IDs[j_]])
print(ans)

Submission status: Accepted

Solution code:
def Find(x, par):
  if par[x] < 0:
    return x
  else:
    par[x] = Find(par[x], par)
    return par[x]

def Unite(x, y, par, rank):
  x = Find(x, par)
  y = Find(y, par)
  
  if x != y:
    if rank[x] < rank[y]:
      par[x] = y
    else:
      par[y] = x
      if rank[x] == rank[y]:
        rank[x] += 1
    
def Same(x, y, par):
  return Find(x, par) == Find(y, par)
 
n, k, l = map(int, input().split())
rpar = [-1]*n
tpar = [-1]*n
rrank = [0]*n
trank = [0]*n
 
for i in range(k):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, rpar, rrank) 

for i_ in range(l):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, tpar, trank)

d = {}
IDs = [0]*n
for j in range(n):
  ID = Find(j, rpar)+(Find(j, tpar)+1)*10**8
  IDs[j] = ID
  if ID in d:
    d[ID] += 1
  else:
    d[ID] = 1

ans = []
for j in range(n):
    ans.append(d[IDs[j]])
print(*ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 11:26:39 2019
D - 連結 / Connectivity
実行時間制限: 2 sec / メモリ制限: 256 MB

配点 : 
400 点
@author: justwah
"""
from collections import Counter

class UnionFind:
    def __init__(self, N):
        self.rank = [0]*N
        self.parent = [i for i in range(N)]
        self.n = 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 merge(self, a, b):
        a = self.root(a)
        b = self.root(b)
        if a == b:
            return
        if self.rank[a] < self.rank[b]:
            self.parent[a] = b
        else:
            self.parent[b] = a
            if self.rank[a] == self.rank[b]:
                self.rank[a] +=1
                
    def same(self, a, b):
        return self.root(a) == self.roob(b)


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

uf_road = UnionFind(n)
for _ in range(k):
    p, q = map(int, input().split())
    uf_road.merge(p-1, q-1)

uf_rail = UnionFind(n)
for _ in range(l):
    r, s = map(int, input().split())
    uf_rail.merge(r-1, s-1)
    
ctr = Counter()
for i in range(n):  # make a list to count number of cities that both road and rail-wise are in the same group
    r1 = uf_road.root(i)
    r2 = uf_rail.root(i)
    ctr[(r1,r2)] += 1

ans = []
for i in range(n): # print the group size of that city when looped
    r1 = uf_road.root(i)
    r2 = uf_rail.root(i)
    ans.append(ctr[(r1,r2)])

print(*ans)   # * is for unpack the list

Submission status: Accepted

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

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

    def root(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.root(self.par[x]) # contraction
            return self.par[x]

    def unite(self, x, y):
        x, y = self.root(x), self.root(y)
        if x != y:
            if self.par[x] > self.par[y]: # merge technique
                x, y = y, x
            self.par[x] += self.par[y]
            self.par[y] = x

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

    def size(self, x):
        return -self.par[self.root(x)]

n, k, l = map(int, input().split())
uf_r = UnionFind(n)
for i in range(k):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf_r.unite(p, q)
uf_t = UnionFind(n)
for i in range(l):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    uf_t.unite(r, s)

root_r = defaultdict(set)
root_t = defaultdict(set)
for i in range(n):
    root_r[uf_r.root(i)].add(i)
    root_t[uf_t.root(i)].add(i)

ans = []
memo = defaultdict(int)
for i in range(n):
    memo[(uf_r.root(i), uf_t.root(i))] += 1
for i in range(n):
    ans.append(memo[(uf_r.root(i), uf_t.root(i))])

print(*ans)

Submission status: Accepted

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

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

    def root(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.root(self.par[x]) # contraction
            return self.par[x]

    def unite(self, x, y):
        x, y = self.root(x), self.root(y)
        if x != y:
            if self.par[x] > self.par[y]: # merge technique
                x, y = y, x
            self.par[x] += self.par[y]
            self.par[y] = x

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

    def size(self, x):
        return -self.par[self.root(x)]

n, k, l = map(int, input().split())
uf_r = UnionFind(n)
for i in range(k):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf_r.unite(p, q)
uf_t = UnionFind(n)
for i in range(l):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    uf_t.unite(r, s)

root_r = defaultdict(set)
root_t = defaultdict(set)
for i in range(n):
    root_r[uf_r.root(i)].add(i)
    root_t[uf_t.root(i)].add(i)

ans = []
memo = dict()
for i in range(n):
    if (uf_r.root(i), uf_t.root(i)) not in memo:
        memo[(uf_r.root(i), uf_t.root(i))] = len(root_r[uf_r.root(i)] & root_t[uf_t.root(i)])
    ans.append(memo[(uf_r.root(i), uf_t.root(i))])

print(*ans)

Submission status: Accepted

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

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

    def root(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.root(self.par[x]) # contraction
            return self.par[x]

    def unite(self, x, y):
        x, y = self.root(x), self.root(y)
        if x != y:
            if self.par[x] > self.par[y]: # merge technique
                x, y = y, x
            self.par[x] += self.par[y]
            self.par[y] = x

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

    def size(self, x):
        return -self.par[self.root(x)]

n, k, l = map(int, input().split())
uf_r = UnionFind(n)
for i in range(k):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf_r.unite(p, q)
uf_t = UnionFind(n)
for i in range(l):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    uf_t.unite(r, s)

root_r = defaultdict(set)
root_t = defaultdict(set)
for i in range(n):
    root_r[uf_r.root(i)].add(i)
    root_t[uf_t.root(i)].add(i)

ans = []
memo = dict()
for i in range(n):
    if (uf_r.root(i), uf_t.root(i)) not in memo:
        memo[(uf_r.root(i), uf_t.root(i))] = len(root_r[uf_r.root(i)] & root_t[uf_t.root(i)])
    ans.append(str(memo[(uf_r.root(i), uf_t.root(i))]))

print(' '.join(ans))

Submission status: Accepted

Solution code:

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
##############################

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

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

# https://atcoder.jp/contests/abc049/submissions/3095247

from collections import Counter

N,K,L = map(int,input().split())
roads = [tuple(map(lambda x:int(x)-1,input().split())) for i in range(K)]
rails = [tuple(map(lambda x:int(x)-1,input().split())) for i in range(L)]

uf_road = UnionFind(N)
for a,b in roads:
    uf_road.unite(a,b)

uf_rail = UnionFind(N)
for a,b in rails:
    uf_rail.unite(a,b)

ctr = Counter()
for i in range(N):
    r1 = uf_road.find(i)
    r2 = uf_rail.find(i)
    ctr[(r1,r2)] += 1

ans = []
for i in range(N):
    r1 = uf_road.find(i)
    r2 = uf_rail.find(i)
    ans.append(ctr[(r1,r2)])

print(*ans)

Submission status: Accepted

Solution code:
from collections import defaultdict as dd
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.root = [-1]*(n+1)
    self.rnk = [0]*(n+1)

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

  def Unite(self, x, y):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if(x == y):
      return 
    elif(self.rnk[x] > self.rnk[y]):
      self.root[x] += self.root[y]
      self.root[y] = x
    else:
      self.root[y] += self.root[x]
      self.root[x] = y
      if(self.rnk[x] == self.rnk[y]):
        self.rnk[y] += 1

  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
    
  def Count(self, x):
    return -self.root[self.Find_Root(x)]
N, K, L = map(int, input().split())
k = UnionFind(N)
l = UnionFind(N)
checkset = set()
res = [1] * (N + 1)
roots = dd(int)
for _ in range(K):
  x, y = map(int, input().split())
  k.Unite(x, y)
  checkset.add(x)
  checkset.add(y)
for _ in range(L):
  x, y = map(int, input().split())
  l.Unite(x, y)
  checkset.add(x)
  checkset.add(y)
for i in list(checkset):
  kr = k.Find_Root(i)
  lr = l.Find_Root(i)
  roots[(kr, lr)] += 1
#print(roots)
for i in list(checkset):
  kr = k.Find_Root(i)
  lr = l.Find_Root(i)
  res[i] = roots[(kr, lr)]
  
print(*(res[1: ]))

Submission status: Accepted

Solution code:
def bfs(n):
    graph = [[] for i in range(N)]

    for i in range(n):
        v, u = map(int, input().split())
        graph[v-1].append(u-1)
        graph[u-1].append(v-1)
    
    root = [i for i in range(N)]
    visited = [False] * N
    
    for i in range(N):
        if not visited[i]:
            q = graph[i]
            visited[i] = True
            
            while q:
                v = q.pop()
                root[v] = i
                visited[v] = True
                for u in graph[v]:
                    if not visited[u]:
                        visited[u] = True
                        q.append(u)
                        root[u] = i
                        
    return root

def main():
    load_root = bfs(K)
    train_root = bfs(L)
    
    count = {}
    
    city = [(i, j) for i, j in zip(load_root, train_root)]
    
    for c in city:
        if c in count:
            count[c] += 1
        else:
            count[c] = 1
            
    for c in city:
        print(count[c], '', end='')

if __name__ == '__main__':
    N, K, L = map(int, input().split())
    main()

Submission status: Accepted

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

#Union-Find
par=[-1 for i in range(n+1)]
def root(a):
    if par[a]<0:
        return a
    else:
        return root(par[a])
def f(a):
    if road[a]<0:
        return a
    else:
        return f(road[a])
def f2(a):
    if rail[a]<0:
        return a
    else:
        return f2(rail[a])
def size(a):
    return -par[root(a)]
def connect(a,b):
    a=root(a)
    b=root(b)
    if a==b:
        return False
    if size(a)<size(b):
        a,b=b,a
    par[a]+=par[b]
    par[b]=a
    return True

for i in range(k):
    a=[int(j) for j in input().split()]
    if root(a[0])!=root(a[1]):
        connect(a[0],a[1])
import copy
road=copy.deepcopy(par)

par=[-1 for i in range(n+1)]

for i in range(l):
    r,s=[int(j) for j in input().split()]
    if root(r)!=root(s):
        connect(r,s)
import copy
rail=copy.deepcopy(par)
l=[(f(i),f2(i)) for i in range(1,1+n)]
from collections import Counter
c=Counter(l)
print(*(c[i] for i in l))

Submission status: Accepted

Solution code:
class UnionFind:
    def __init__(self, N):
        self.parent = [x for x in range(N+1)]
        self.rank = [1 for x in range(N+1)]

    def find(self, x):
        p = x
        while self.parent[p] != p:
            p = self.parent[p]
        self.parent[x] = p
        return p

    def union(self, r, l):
        x, y = self.find(r), self.find(l)
        if x == y:
            return
        rx, ry = self.rank[x], self.rank[y]
        if rx > ry:
            self.parent[y] = x
        elif rx == ry:
            self.parent[y] = x
            self.rank[x] += 1
        else:
            self.parent[x] = y

def main():
    N, K, L = map(int, input().split())
    
    rails = UnionFind(N)
    for _ in range(K):
        p, q = map(int, input().split())
        rails.union(p, q)

    loads = UnionFind(N)
    for _ in range(L):
        p, q = map(int, input().split())
        loads.union(p,q)
    RL = [(rails.find(u), loads.find(u)) for u in range(1, N+1)]
    from collections import Counter
    c = Counter(RL)

    print(*(c[x] for x in RL))

main()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline

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

city_road_train=set()

city_roadgroup_dict={}
roadgroup_city_dict={}

city_traingroup_dict={}
traingroup_city_dict={}

for ch_pq in pq:

  if not ch_pq[0] in city_roadgroup_dict:
    if not ch_pq[1] in city_roadgroup_dict:
      new_group_num=ch_pq[0]
      city_roadgroup_dict[ch_pq[0]]=new_group_num
      city_roadgroup_dict[ch_pq[1]]=new_group_num
      roadgroup_city_dict[new_group_num]=set([ch_pq[0],ch_pq[1]])
    else:
      group_num=city_roadgroup_dict[ch_pq[1]]
      city_roadgroup_dict[ch_pq[0]]=group_num
      roadgroup_city_dict[group_num].add(ch_pq[0])
  else:
    if not ch_pq[1] in city_roadgroup_dict:
      group_num=city_roadgroup_dict[ch_pq[0]]
      city_roadgroup_dict[ch_pq[1]]=group_num
      roadgroup_city_dict[group_num].add(ch_pq[1])
    else:
      group_num_0=city_roadgroup_dict[ch_pq[0]]
      group_num_1=city_roadgroup_dict[ch_pq[1]]
      if group_num_0!=group_num_1:
        group_0=roadgroup_city_dict[group_num_0]
        group_1=roadgroup_city_dict[group_num_1]
        if len(group_0)<len(group_1):
          for city_n in list(group_0):
            city_roadgroup_dict[city_n]=group_num_1
          roadgroup_city_dict[group_num_1]|=group_0
          del roadgroup_city_dict[group_num_0]

        else:
          for city_n in list(group_1):
            city_roadgroup_dict[city_n]=group_num_0
          roadgroup_city_dict[group_num_0]|=group_1
          del roadgroup_city_dict[group_num_1]


for ch_rs in rs:
  for rs_i in range(2): 
    if not ch_rs[rs_i] in city_road_train and ch_rs[rs_i] in city_roadgroup_dict:
      city_road_train.add(ch_rs[rs_i])
  
  if not ch_rs[0] in city_traingroup_dict:
    if not ch_rs[1] in city_traingroup_dict:
      new_group_num=ch_rs[0]
      city_traingroup_dict[ch_rs[0]]=new_group_num
      city_traingroup_dict[ch_rs[1]]=new_group_num
      traingroup_city_dict[new_group_num]=set([ch_rs[0],ch_rs[1]])
    else:
      group_num=city_traingroup_dict[ch_rs[1]]
      city_traingroup_dict[ch_rs[0]]=group_num
      traingroup_city_dict[group_num].add(ch_rs[0])
  else:
    if not ch_rs[1] in city_traingroup_dict:
      group_num=city_traingroup_dict[ch_rs[0]]
      city_traingroup_dict[ch_rs[1]]=group_num
      traingroup_city_dict[group_num].add(ch_rs[1])
    else:
      group_num_0=city_traingroup_dict[ch_rs[0]]
      group_num_1=city_traingroup_dict[ch_rs[1]]
      if group_num_0!=group_num_1:
        group_0=traingroup_city_dict[group_num_0]
        group_1=traingroup_city_dict[group_num_1]
        if len(group_0)<len(group_1):
          for city_n in list(group_0):
            city_traingroup_dict[city_n]=group_num_1
          traingroup_city_dict[group_num_1]|=group_0
          del traingroup_city_dict[group_num_0]

        else:
          for city_n in list(group_1):
            city_traingroup_dict[city_n]=group_num_0
          traingroup_city_dict[group_num_0]|=group_1
          del traingroup_city_dict[group_num_1]
          
city_both_conn_num=['1']*N
ched_city=set()
for ch_city in list(city_road_train):
  if not ch_city in ched_city:
    road_group_num=city_roadgroup_dict[ch_city]
    train_group_num=city_traingroup_dict[ch_city]
    intersect_group=roadgroup_city_dict[road_group_num] & traingroup_city_dict[train_group_num]
    ched_city|=intersect_group
    
    conn_size=str(len(intersect_group))
    for conn_city in list(intersect_group):
      city_both_conn_num[conn_city-1]=conn_size


print(' '.join(city_both_conn_num))

Submission status: Accepted

Solution code:
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.root = [-1]*(n+1)
    self.rank = [0]*(n+1)
  
  def Find_Root(self, x):
    if self.root[x] < 0:
      return x
    else:
      self.root[x] = self.Find_Root(self.root[x])
      return self.root[x]
    
  def Unite(self, x, y):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if x == y:
      return
    elif self.rank[x] > self.rank[y]:
        self.root[x] += self.root[y]
        self.root[y] = x
    else:
        self.root[y] += self.root[x]
        self.root[x] = y
        if self.rank[x] == self.rank[y]:
          self.rank[y] += 1
  def Is_Same_Group(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
  
  def Count(self, x):
    return -self.root[self.Find_Root(x)]

n,k,l=map(int,input().split())
douro=UnionFind(n)
tetudou=UnionFind(n)
for i in range(k):
  p,q=map(int,input().split())
  douro.Unite(p-1, q-1)
for i in range(l):
  r,s=map(int,input().split())
  tetudou.Unite(r-1, s-1)

d={}
for i in range(n):
  pair=(douro.Find_Root(i), tetudou.Find_Root(i))
  if pair in d:
    d[pair] += 1
  else:
    d[pair] = 1

print(' '.join([str(d[(douro.Find_Root(i), tetudou.Find_Root(i))]) for i in range(n)]))

Submission status: Accepted

Solution code:
def root(x,par):
    if x == par[x]:
        return x
    else:
        par[x] = root(par[x],par)
        return par[x]
 
def unite(x,y,par):
    x = root(x,par)
    y = root(y,par)
    if x==y:
        if x==0 and y==1:
            return
    else:
        par[x]=y

n,k,l = map(int,input().split())
road =[i for i in range(n)]
train = [i for i in range(n)]
ans =0
for _ in range(k):
    p,q = map(int,input().split())
    unite(p-1,q-1,road)
for _ in range(l):
    p,q = map(int,input().split())
    unite(p-1,q-1,train)

for i in range(n):
    root(i,train)
for i in range(n):
    root(i,road)

dual = [(i,j) for i,j in zip(road,train)]
ans ={}
for i in dual:
    if i in ans:
        ans[i] +=1
    else:
        ans[i] =1
for i in dual:
    print(ans[i],end=" ")

Submission status: Accepted

Solution code:
from collections import deque
from sys import stdin

def create_links(n, k):
  links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, stdin.readline().split())
    links[p - 1].append(q - 1)
    links[q - 1].append(p - 1)
  return links

def create_groups(n, links):
  groups = list(range(n))
  for i in range(n):
    if groups[i] != i:
      continue
    d = deque()
    d.append(i)
    while len(d) != 0:
      j = d.popleft()
      for k in links[j]:
        if groups[k] != i:
          groups[k] = i
          d.append(k)
  return groups

n, k, l = map(int, input().split())
road_links = create_links(n, k)
rail_links = create_links(n, l)
road_groups = create_groups(n, road_links)
rail_groups = create_groups(n, rail_links)

d = {}
for i in range(n):
  t = (road_groups[i], rail_groups[i])
  if t in d:
    d[t] += 1
  else:
    d[t] = 1

print(*[d[(road_groups[i], rail_groups[i])] for i in range(n)])

Submission status: Accepted

Solution code:
from sys import stdin

def create_links(n, k):
  links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, stdin.readline().split())
    links[p - 1].append(q - 1)
    links[q - 1].append(p - 1)
  return links

def create_groups(n, links):
  groups = list(range(n))
  for i in range(n):
    if groups[i] != i:
      continue
    q = [i]
    while q:
      j = q.pop()
      for k in links[j]:
        if groups[k] != i:
          groups[k] = i
          q.append(k)
  return groups

n, k, l = map(int, input().split())
road_links = create_links(n, k)
rail_links = create_links(n, l)
road_groups = create_groups(n, road_links)
rail_groups = create_groups(n, rail_links)

d = {}
for i in range(n):
  t = (road_groups[i], rail_groups[i])
  if t in d:
    d[t] += 1
  else:
    d[t] = 1

print(*[d[(road_groups[i], rail_groups[i])] for i in range(n)])