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())
 
road = [i for i in range(N)]
rail = [i for i in range(N)]
rank = [0 for i in range(N)]
 
def find(a, U):
  if a == U[a]:
    return a
  else:
    par = find(U[a], U)
    U[a] = par
    return par
  
for i in range(K):
  p, q = map(int,input().split())
  p -= 1
  q -= 1  
  a = find(p, road)
  b = find(q, road)
 
  road[a] = b
  
for i in range(L):
  p, q = map(int,input().split())
  p -= 1
  q -= 1  
  a = find(p, rail)
  b = find(q, rail)
 
  rail[a] = b
  
for i in range(N):
  #print(road, rail)
  road[i] = find(road[i],road)
  rail[i] = find(rail[i],rail)
  
rr = [(road[i], rail[i]) for i in range(N)]
D = {}
for r in rr:
  if not r in D:
    D[r] = 1
  else:
    D[r] += 1
#print(road,rail)
#print(D)
 
for i in range(N):
  print(D[(road[i],rail[i])])

Submission status: Accepted

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

def root(x):
  while p[x]>=0:
    x=p[x]
  return x

def unite(x,y):
  x,y=root(x),root(y)
  if x==y: return
  if x>y: x,y=y,x
  p[x]+=p[y]
  p[y]=x

def g(x):
  global p
  p=[-1]*N
  for _ in range(x):
    a,b=map(int,input().split())
    unite(a-1,b-1)
  return [root(i) for i in range(N)]

z=[*zip(g(K),g(L))]
cnt=Counter(z)
print(*[cnt[t] for t in z])

Submission status: Accepted

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

class UnionFind():
    def __init__(self, n):
        # size of n.
        self.n = n
        # n's parent. default is -1.
        self.parents = [-1] * n

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

    def union_merge(self, x, y):
        x = self.find_root(x)
        y = self.find_root(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

    # You shouldn't use these below for optimization.
    # Use only find_root to compare if you need.
    def union_size(self, x):
        # Root value's index has its size with negative.
        return -self.parents[self.find_root(x)]

    def is_same_union(self, x, y):
        return self.find_root(x) == self.find_root(y)

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

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

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

    def all_unions(self):
        return [self.same_union_members(r) for r in self.roots()]

road = UnionFind(N)
rail = UnionFind(N)

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

for i in range(L):
    r, s = map(int, input().split())
    rail.union_merge(r-1, s-1)

root_combinations = []
for i in range(N):
    root_combinations.append((road.find_root(i), rail.find_root(i)))

from collections import Counter
same_combinations = Counter(root_combinations)
result = [same_combinations[root_combination] for root_combination in root_combinations]

ans = ' '.join(map(str, result))
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

# def components(n,k,e):
#     ed=defaultdict(lambda:deque())
#     for edge in e:
#         ed[edge[0]].append(edge[1])
#     c=0
#     s=[0]*n
#     label=[0]*n
#     for i in range(1,n+1):
#         if s[i-1]==0:
#             c+=1
#             label[c-1]=c
#             stack=deque([i])
#             while stack:
#                 w=stack.pop()
#                 s[w-1]=c
#                 while ed[w]:
#                     wn=ed[w].pop()
#                     if s[wn-1]==0:
#                         s[wn-1]=c
#                         if ed[wn]:
#                             stack.append(w)
#                             w=wn
#                     elif s[wn-1]<c:
#                         label[s[wn-1]-1]=c
#     print(s)
#     print(label)
#     return [label[s[i]-1] for i in range(n)] 
           
def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
        ed[edge[1]].append(edge[0])
    c=0
    s=[0]*n
    stack=deque()
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            stack.clear()
            stack.append(i)
            while stack:
                w=stack.pop()
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
    return [s[i] for i in range(n)] 

def components2(n,k,e):
    es=deque(set((edge[0],edge[1])) for edge in e)
    c=0
    s=deque()
    stack=deque()
    while es:
        f=es.pop()
        stack.clear()
        while es:
            l=len(es)
            g=es.pop()
            if g&f:
                f|=g
            else:
                stack.append(g)
            if l==len(stack):
                s.append(f)
                break
            es=stack
    t=[0]*n
    c=0
    while s:
        for x in s.pop():
            t[x-1]=c
        c+=1
    return t
                
                
        
        
def main(n,k,l,e1,e2):
    d1=components(n,k,e1)
    d2=components(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Accepted

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
    c=0
    s=[0]*n
    label=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            label[c-1]=c
            stack=deque([i])
            while stack:
                w=stack.pop()
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
                    elif s[wn-1]<c:
                        label[s[wn-1]-1]=c
    return [label[s[i]-1] for i in range(n)] 
           
def components2(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
        ed[edge[1]].append(edge[0])
    c=0
    s=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            stack=deque([i])
            while stack:
                w=stack.pop()
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
    return [s[i] for i in range(n)] 
def main(n,k,l,e1,e2):
    d1=components2(n,k,e1)
    d2=components2(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Accepted

Solution code:
#Union Find
class union_find:
    #初期化
    #根なら-size,子なら親の頂点
    # par = [-1]*N
    def __init__(self, N):
        self.par = [-1]*N

    #xの根を求める
    def find(self, x):
        if self.par[x] < 0:
            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 False
        else:
            #sizeの大きいほうがx
            if self.par[x] > self.par[y]:
                x,y = y,x
            self.par[x] += self.par[y]
            self.par[y] = x
            return True

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

    #xが属する集合の個数
    def size(self, x):
        return -self.par[self.find(x)]

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


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

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

pairs = [(uf1.find(i), uf2.find(i)) for i in range(N)]
from collections import Counter

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

Submission status: Accepted

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
        ed[edge[1]].append(edge[0])
    c=0
    s=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            stack=deque([i])
            while stack:
                w=stack.pop() 
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
    return s
           
def main(n,k,l,e1,e2):
    d1=components(n,k,e1)
    d2=components(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    d[(k,l)]=1
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Accepted

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def main(n,k,l,e1,e2):
    d1=conn(n,k,e1)
    d2=conn(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    d[(k,l)]=1
    print(' '.join([str(d[x]) for x in p]))

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Accepted

Solution code:
#from heapq import heapify,heappush,heappop
N, K, L = map(int,input().split())

road = [i for i in range(N)]
rail = [i for i in range(N)]
rank = [0 for i in range(N)]

def find(a, U):
  if a == U[a]:
    return a
  else:
    par = find(U[a], U)
    U[a] = par
    return par
  
for i in range(K):
  p, q = map(int,input().split())
  p -= 1
  q -= 1  
  a = find(p, road)
  b = find(q, road)

  road[a] = b
  
for i in range(L):
  p, q = map(int,input().split())
  p -= 1
  q -= 1  
  a = find(p, rail)
  b = find(q, rail)

  rail[a] = b
  
for i in range(N):
  #print(road, rail)
  road[i] = find(road[i],road)
  rail[i] = find(rail[i],rail)
  
rr = [(road[i], rail[i]) for i in range(N)]
D = {}
for r in rr:
  if not r in D:
    D[r] = 1
  else:
    D[r] += 1
#print(road,rail)
#print(D)

for i in range(N):
  print(D[(road[i],rail[i])])

Submission status: Accepted

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

class UnionFind(object):
    def __init__(self, n):
        self._par = list(range(n))
        self.size = [1] * n
 
    def root(self, v):
        if self._par[v] == v:
            return v
        self._par[v] = self.root(self._par[v])
        return self._par[v]
 
    def unite(self, u, v):
        u, v = self.root(u), self.root(v)
        if u == v:
            return False
        if self.size[u] > self.size[v]:
            u, v = v, u # size[u] <= size[v]
        self.size[v] += self.size[u]
        self._par[u] = v
 
    def is_connected(self, u, v):
        return self.root(u) == self.root(v)


rood = UnionFind(n)
train = UnionFind(n)

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

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


from collections import Counter
cnt = Counter()
for i in range(n):
    root_r, root_t = rood.root(i), train.root(i)
    cnt[(root_r, root_t)] += 1

ans = []
for i in range(n):
    root_r, root_t = rood.root(i), train.root(i)
    ans.append(cnt[(root_r, root_t)])

print(*ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
class unionfind:#早いunionfind,class[i]のように要素指定すると親を得ることができる
    def __init__(self, elements=None):#elementsで初期化
        if elements is None:
            elements = ()
        self.parents = {}
        self.weights = {}
        for x in elements:
            self.weights[x] = 1
            self.parents[x] = x

    def __getitem__(self, i):
        # check for previously unknown i
        if i not in self.parents:
            self.parents[i] = i
            self.weights[i] = 1
            return i
        path = [i]
        root = self.parents[i]
        while root != path[-1]:
            path.append(root)
            root = self.parents[root]
        for ancestor in path:#縮約
            self.parents[ancestor] = root
        return root

    def __iter__(self):#for parent in Class:
        return iter(self.parents)

    def union(self, *objects):#オブジェクトをすべて結合
        roots = [self[x] for x in objects]
        heaviest = max(roots, key=lambda r: self.weights[r])
        for r in roots:
            if r != heaviest:
                self.weights[heaviest] += self.weights[r]
                self.parents[r] = heaviest

    def __len__(self):
        return len(self.parents)

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, K, L = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
     #改行行列
    train=unionfind(range(N))
    rail=unionfind(range(N))

    for i in range(K):#木の場合M=N-1
        a,b = map(int,input().split())
        train.union(a-1,b-1)

    S = tuple(tuple(map(int, input().split())) for i in range(L))
    for a,b in S:#木の場合M=N-1
        a-=1
        b-=1
        rail.union(a,b)

    
    c=Counter()

    ans=[0]*N

    for i in range(N):
        c[rail[i]*N+train[i]]+=1
    for i in range(N):
        ans[i]=c[rail[i]*N+train[i]]
    print(*ans)
        
    





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
f=lambda:map(int,input().split())
n,k,l=f()
def root(x):
  while p[x]>=0: x=p[x]
  return x
def unite(x,y):
  x,y=root(x),root(y)
  if x==y: return
  if x>y: x,y=y,x
  p[x]+=p[y]
  p[y]=x
def g(x):
  global p
  p=[-1]*n
  for _ in range(x):
    a,b=f()
    unite(a-1,b-1)
  return [root(i) for i in range(n)]
from collections import *
z=[*zip(g(k),g(l))]
C=Counter(z)
print(*[C[t] for t in z])

Submission status: Accepted

Solution code:
f=lambda:map(int,input().split())
n,k,l=f()
def root(x):
  while p[x]>=0: x=p[x]
  return x
def unite(x,y):
  x,y=root(x),root(y)
  if x==y: return
  if x>y: x,y=y,x
  p[x]+=p[y]
  p[y]=x
def g(x):
  global p
  p=[-1]*n
  for _ in range(x):
    a,b=f()
    unite(a-1,b-1)
  return [root(i) for i in range(n)]
H,R=g(k),g(l)
from collections import *
z=[*zip(H,R)]
C=Counter(z)
print(*[C[t] for t in z])

Submission status: Accepted

Solution code:
f=lambda:map(int,input().split())
n,k,l=f()
def root(x):
  while p[x]>=0: x=p[x]
  return x
def unite(x,y):
  x,y=root(x),root(y)
  if x==y: return
  if x>y: x,y=y,x
  p[x]+=p[y]
  p[y]=x
def same(x,y):
  return root(x)==root(y)
def size(x):
  return -p[root(x)]
def root_all(x):
  global p
  p=[-1]*n
  for _ in range(x):
    a,b=f()
    unite(a-1,b-1)
  return [root(i) for i in range(n)]
H,R=root_all(k),root_all(l)
from collections import *
z=[*zip(H,R)]
C=Counter(z)
print(*[C[t] for t in z])

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from collections import Counter

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

def main():
    N, K, L = map(int, readline().rstrip().split())
    uf_road = UnionFind(N)
    uf_train = UnionFind(N)
    
    for _ in range(K):
        p, q = map(int, readline().rstrip().split())
        uf_road.union(p-1, q-1)
    
    for _ in range(L):
        r, s = map(int, readline().rstrip().split())
        uf_train.union(r-1, s-1)
    
    pairs = []
    for i in range(N):
        pairs.append((uf_road.find(i), uf_train.find(i)))
    
    cnt = Counter(pairs)
    res = [cnt[pair] for pair in pairs]
    print(*res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
def root(x, par):
    while par[x] >= 0:
        x = par[x]
    return x

def unite(x,y,par):
    rx = root(x,par)
    ry = root(y,par)
    if rx != ry:
        if rx > ry:
            rx, ry = ry, rx
        par[rx] += par[ry]
        par[ry] = rx

def same(x,y,par):
    rx = root(x,par)
    ry = root(y,par)
    return rx == ry

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

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

for i in range(K):
    A, B = map(int, input().split())
    A, B = A-1, B-1
    unite(A, B, par1)

for i in range(L):
    C, D = map(int, input().split())
    C, D = C-1, D-1
    unite(C, D, par2)

G = defaultdict(list)
for i in range(N):
    G[(root(i, par1), root(i, par2))].append(i)
Ans = [0]*N
for city_list in G.values():
    for city in city_list:
        Ans[city] = len(city_list)
for i in Ans:
    print(i, end=" ")

Submission status: Accepted

Solution code:
from collections import defaultdict


class DisjointSet:

    def __init__(self, N):
        self.parents = [i for i in range(N)]
        self.count = N

    def find(self, x):
        path = []
        while self.parents[x] != x:
            x = self.parents[x]
            path.append(x)
        for p in path:
            self.parents[p] = x
        return x

    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if self.find(root_x) != self.find(root_y):
            self.parents[root_x] = root_y
            self.count -= 1


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def read_oneless_ints():
    return [int(a)-1 for a in input().strip().split(' ')]


def solve():
    N, K, L = read_ints()
    disjoint_set_roads = DisjointSet(N)
    disjoint_set_railways = DisjointSet(N)

    for _ in range(K):
        u, v = read_oneless_ints()
        disjoint_set_roads.union(u, v)
    for _ in range(L):
        u, v = read_oneless_ints()
        disjoint_set_railways.union(u, v)
    G = defaultdict(list) # (p1, p2) -> [nodes]
    for i in range(N):
        G[(disjoint_set_roads.find(i), disjoint_set_railways.find(i))].append(i)
    answer = [None]*N
    for city_list in G.values():
        for city in city_list:
            answer[city] = len(city_list)
    for a in answer:
        print(a)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import numpy as np
from collections import Counter
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

int1 = lambda x: int(x) - 1
N, K, L = map(int, input().split())
roads = np.array([tuple(map(int1, input().split())) for _ in range(K)]).T
railways = np.array([tuple(map(int1, input().split())) for _ in range(L)]).T


def connected(G, M):
    matr = csr_matrix((np.ones(M, dtype=int), G), shape=(N, N))
    _, labels = connected_components(matr)
    return labels


roads_connection = connected(roads, K).tolist()
railways_connection = connected(railways, L).tolist()

ct = Counter((roads_connection[i], railways_connection[i]) for i in range(N))
ans = [ct[(roads_connection[i], railways_connection[i])] for i in range(N)]
print(*ans)

Submission status: Accepted

Solution code:
n,k,l=map(int,input().split())
load=[[] for _ in range(n)]
train=[[] for _ in range(n)]
for _ in range(k):
  a,b=map(int,input().split())
  a-=1
  b-=1
  load[a].append(b)
  load[b].append(a)
for _ in range(l):
  a,b=map(int,input().split())
  a-=1
  b-=1
  train[a].append(b)
  train[b].append(a)

# 道路の連結グループ
load_grp_id=[-1]*n
not_grp=set(range(n))
while not_grp:
  t0=not_grp.pop()
  todo=[t0]
  load_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    l=load[t]
    for li in l:
      if load_grp_id[li]==-1:
        load_grp_id[li]=t0
        not_grp.discard(li)
        todo.append(li)
# 鉄道の連結グループ
train_grp_id=[-1]*n
not_grp=set(range(n))
while not_grp:
  t0=not_grp.pop()
  todo=[t0]
  train_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    l=train[t]
    for li in l:
      if train_grp_id[li]==-1:
        train_grp_id[li]=t0
        not_grp.discard(li)
        todo.append(li)

d={}
for i in range(n):
  lid=load_grp_id[i]
  tid=train_grp_id[i]
  if (lid,tid) in d:
    d[(lid,tid)]+=1
  else:
    d[(lid,tid)]=1
ans=[]
for i in range(n):
  lid=load_grp_id[i]
  tid=train_grp_id[i]
  ans.append(str(d[(lid,tid)]))
print(' '.join(ans))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
from collections import Counter
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
    #木の深さじゃなく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())
load=UnionFind(n+1)
tetsu=UnionFind(n+1)
for _ in range(k):
    p,q=map(int,input().split())
    load.union(p,q)
for _ in range(l):
    r,s = map(int,input().split())
    tetsu.union(r,s)

count = [(load.find(i),tetsu.find(i)) for i in range(1,n+1)]
# print(count)
C = Counter(count)
ans = []
for i in range(n):
	if count[i][0]<0 or count[i][1]<0:
		ans.append(0)
	else:
		ans.append(C[count[i]])
print(*ans)