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 Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.children = []
        self.size = 1
    
class UF:
    def __init__(self, size):
        self.n = size
        self.parents = [i for i in range(self.n+1)]
        self.sizes = [1] * (self.n+1)
        self.nodes = [None]
        for i in range(1, self.n+1):
            self.nodes.append(Node(i))
        

    def get_parent(self, x):
        while x.parent != None:
            x = x.parent
        return x

    def union(self, x, y):
        x = self.nodes[x]
        y = self.nodes[y]
        xp = self.get_parent(x)
        yp = self.get_parent(y)
        if xp == yp and xp is not None and yp is not None:
            return
        if xp.size >= yp.size:
            xp.children.append(yp)
            xp.size += yp.size
            self.sink(xp, yp)
        else:
            yp.children.append(xp)
            yp.size += xp.size
            self.sink(yp, xp)

    def sink(self, xp, yp):
        yp.parent = xp
        self.parents[yp.key] = xp.key
        yp.size = xp.size
        for child in yp.children:
            self.sink(xp, child)
            
from collections import defaultdict
n, k, l = map(int, raw_input().split())
uf1 = UF(n)
for i in range(k):
    p, q = map(int, raw_input().split())
    uf1.union(p, q)
uf2 = UF(n)
for i in range(l):
    r, s = map(int, raw_input().split())
    uf2.union(r, s)
p1 = uf1.parents
p2 = uf2.parents
dic = defaultdict(int)
for i in range(1, n+1):
    key = (p1[i], p2[i])
    dic[key] += 1
res_arr = []
for i in range(1, n+1):
    if uf1.nodes[i].size == 1 or uf2.nodes[i].size == 1:
        res_arr.append(1)
    else:
        key = (p1[i], p2[i])
        res_arr.append(dic[key])
print " ".join(map(str, res_arr))

Submission status: Accepted

Solution code:
class Tree():
  def __init__(s, n):
    s.L = [-1] * n
  def root(s, x):
    if s.L[x] < 0:
      return x, -s.L[x]
    a, b = s.root(s.L[x])
    s.L[x] = a
    return a, b
  def merge(s, a, b):
    ra, sa = s.root(a)
    rb, sb = s.root(b)
    if ra != rb:
      if sa < sb:
        s.L[ra] = rb
        s.L[rb] -= sa
      else:
        s.L[rb] = ra
        s.L[ra] -= sb
      return True
    return False


N, K, L = list(map(int, input().split()))
pq = [list(map(int, input().split())) for _ in range(K)]
rs = [list(map(int, input().split())) for _ in range(L)]

R = Tree(N)
T = Tree(N)

for a, b in pq:
  a -= 1
  b -= 1
  R.merge(a, b)

for a, b in rs:
  a -= 1
  b -= 1
  T.merge(a, b)

RL = [0] * N
for i in range(N):
  RL[i] = R.root(i)[0]

TL = [0] * N
for i in range(N):
  TL[i] = T.root(i)[0]

D = {}
for i in range(N):
  if RL[i] not in D:
    D[RL[i]] = {}
    D[RL[i]][TL[i]] = 1
  else:
    if TL[i] not in D[RL[i]]:
      D[RL[i]][TL[i]] = 1
    else:
      D[RL[i]][TL[i]] += 1

for i in range(N):
  print(D[RL[i]][TL[i]], end = " ")

Submission status: Accepted

Solution code:
# 2019/07/14

from collections import Counter


class unionfind():
    def __init__(self,n):
        self.par=list(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 is_same(self,x,y):
        return self.find(x)==self.find(y)
    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


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

uf1=unionfind(n)
uf2=unionfind(n)

for i in range(k):
    p,q=map(int,input().split())
    uf1.unite(p,q)

for i in range(l):
    r,s=map(int,input().split())
    uf2.unite(r,s)

res=[]

for i in range(n+1):
    tmp=(uf1.find(i),uf2.find(i))
    res.append(tmp)
c=Counter(res)
ans=[]
for i in range(n+1):
    ans.append(c[res[i]])
print(*ans[1:])

Submission status: Accepted

Solution code:
# 2019/07/13
# Union-Find
# Disjoint-Set

import sys
from collections import Counter
input=sys.stdin.readline
sys.setrecursionlimit(10**9)

class union_find():
    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 is_same(self,x,y):
        return self.find(x)==self.find(y)
    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


n,k,l=map(int,input().split())
res=[1]*(n+1)
uf1=union_find(n)
for i in range(k):
    p,q=map(int,input().split())
    uf1.unite(p,q)

uf2=union_find(n)
for i in range(l):
    r,s=map(int,input().split())
    uf2.unite(r,s)

res=[]
for i in range(n+1):
    res.append((uf1.find(i),uf2.find(i)))
c=Counter(res)

ans=[]

for i in range(n+1):
    ans.append(c[res[i]])
print(*ans[1:])

Submission status: Accepted

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

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

vec1, vec2 = [[] for _ in range(N)], [[] for _ in range(N)]

for _ in range(K) :
    p, q = map(int, input().split())
    vec1[p-1].append(q-1)
    vec1[q-1].append(p-1)
for _ in range(L) :
    r, s = map(int, input().split())
    vec2[r-1].append(s-1)
    vec2[s-1].append(r-1)

def bfs(v) :
    visited = [-1] * N
    n = 0
    for i in range(N) :
        if visited[i] < 0 :
            queue = [i]
            visited[i] = n
            j = 0
            while j < len(queue) :
                cur = queue[j]
                for nex in v[cur] :
                    if visited[nex] < 0 :
                        queue.append(nex)
                        visited[nex] = n
                j += 1
            n += 1
            
    return visited
    
visited1 = bfs(vec1)
visited2 = bfs(vec2)
p = [(visited1[i], visited2[i]) for i in range(N)]
c = Counter(p)

print(' '.join([str(c[p[i]]) for i in range(N)]))

Submission status: Accepted

Solution code:
from collections import defaultdict

class UnionFind():

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

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

    def same(self, 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.par[x] = y
        return


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

    # O(K)
    for _ in range(K):
        p, q = map(int, input().split())
        uf1.unite(p-1, q-1)
    
    # O(L)
    for _ in range(L):
        r, s = map(int, input().split())
        uf2.unite(r-1, s-1)

    # O(N) x O(log_N)
    # 理解が少し難しいが、根ペアをキーに加算していく 
    # => 根から見ると、連結している頂点数（自身を含む）を数えている。
    cnts = defaultdict(int)
    for i in range(N):
        pos = (uf1.root(i), uf2.root(i))
        cnts[pos] += 1

    ans = []
    for i in range(N):
        pos = (uf1.root(i), uf2.root(i))
        ans.append(cnts[pos])

    print(*ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

class UnionFind:
    def __init__(self, n):
        self.data = [0] * N
        for i in range(N):
            self.data[i] = i
            
    def get_root(self, x):
        r = self.data[x]
        if r == x:
            return r
        p = self.get_root(r)
        self.data[x] = p
        
        return p
    
    def unite(self, x, y):
        rx = self.get_root(x)
        ry = self.get_root(y)
        
        if rx != ry:
            self.data[rx] = ry

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

N, K, L = map(int, input().split())
LA = [[int(v) - 1 for v in input().split()] for _ in range(K)]
LB = [[int(v) - 1 for v in input().split()] for _ in range(L)]

u1 = UnionFind(N)
for x, y in LA:
    u1.unite(x, y)
    
u2 = UnionFind(N)
for x, y in LB:
    u2.unite(x, y)

result = {}
for i in range(N):
    a = u1.get_root(i)
    b = u2.get_root(i)
    
    if result.get((a, b)) == None:
        result[(a, b)] = 0
    result[(a, b)] += 1
    
for i in range(N):
    a = u1.get_root(i)
    b = u2.get_root(i)
    
    print(result[(a, b)], end = "")
    if i != N - 1:
        print(" ", end = "")
    else:
        print()

Submission status: Accepted

Solution code:
n, k, l = map(int, input().split())
from collections import defaultdict

class UnionFind( ):
    def __init__(self, N):
        self.rank = [0] * N
        self.par = [i for i 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 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[y] = x
        else:
            self.par[x] = y
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

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


uf1 = UnionFind(n)
uf2 = UnionFind(n)

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


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

pair = defaultdict(int)
for i in range(n):
    a = uf1.find(i)
    b = uf2.find(i)
    pair[(a, b)] += 1

ans = []
for i in range(n):
    ans.append(pair[(uf1.find(i), uf2.find(i))])

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

Submission status: Accepted

Solution code:
from collections import Counter

class Union_Find:

    def __init__(self, n):
        self.n = n
        self.par = [i for i in range(n)]
        self.height = [0 for i in range(n)]
        self.size = [1 for i 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 getsize(self, x):
        return self.size[self.find(x)]

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

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

N, K, L = map(int, input().split())
uf0 = Union_Find(N+1)
for i in range(K):
    x, y = map(int, input().split())
    uf0.union(x, y)
uf1 = Union_Find(N+1)
for i in range(L):
    x, y = map(int, input().split())
    uf1.union(x, y)
types = [None] * (N+1)
for i in range(1, N+1):
    types[i] = (uf0.find(i), uf1.find(i))
C = Counter(types)
ans = [None] * (N+1)
for i in range(1, N+1):
    ans[i] = C[types[i]]
print(*ans[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 FindRoot(self,x):
    if self.root[x]<0:
      return x
    else:
      self.root[x]=self.FindRoot(self.root[x])
      return self.root[x]
  def Unite(self,x,y):
    x=self.FindRoot(x)
    y=self.FindRoot(y)
    if x==y:
      return
    else:
      if self.rank[x]>self.rank[y]:
        self.root[x]+=self.root[y]
        self.root[y]=x
      elif self.rank[x]<=self.rank[y]:
        self.root[y]+=self.root[x]
        self.root[x]=y
        if self.rank[x]==self.rank[y]:
          self.rank[y]+=1
  def isSameGroup(self,x,y):
    return self.FindRoot(x)==self.FindRoot(y)
  def Count(self,x):
    return -self.root[self.FindRoot(x)]
  
n,k,l=map(int,input().split())
t1=UnionFind(n)
t2=UnionFind(n)
for _ in range(k):
  a,b=map(int,input().split())
  t1.Unite(a,b)
for _ in range(l):
  a,b=map(int,input().split())
  t2.Unite(a,b)
dic={}
for i in range(1,n+1):
  pos=(t1.FindRoot(i),t2.FindRoot(i))
  if pos not in dic:
    dic[pos]=1
  else:
    dic[pos]+=1
ans=[]
for i in range(1,n+1):
  pos=(t1.FindRoot(i),t2.FindRoot(i))
  ans.append(dic[pos])
print(*ans)

Submission status: Accepted

Solution code:
from collections import Counter
N, K, L = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(K)]
Y = [list(map(int, input().split())) for _ in range(L)]

class UnionFind:
    def __init__(self, n):
        self.par = list(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 x == y:
            return
        
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
                
    def same(self, x, y):
        return self.find(x) == self.find(y)
    
    def __repr__(self):
        return ', '.join(str(x) for x in self.par)

t1 = UnionFind(N)
t2 = UnionFind(N)

for p, q in X:
    t1.unite(p - 1, q - 1)
    
for r, s in Y:
    t2.unite(r - 1, s - 1)

connect = [(t1.find(i), t2.find(i)) for i in range(N)]
ctr = Counter(connect)
print(*[ctr[key] for key in connect])

Submission status: Accepted

Solution code:
import os
import sys
from collections import defaultdict

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18

N, K, L = list(map(int, sys.stdin.readline().split()))
P, Q = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(K)]))
R, S = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(L)]))


class UnionFind:
    def __init__(self, size=None, nodes=None):
        """
        size か nodes どっちか指定。
        nodes は set、size は list を使う。
        set の最悪計算量は O(N) なので size 指定のほうが若干速い
        :param int size:
        :param collections.Iterable nodes:
        """
        assert size is not None or nodes is not None
        if size is not None:
            self._parents = [i for i in range(size)]
            self._ranks = [0 for _ in range(size)]
            self._sizes = [1 for _ in range(size)]
        else:
            self._parents = {k: k for k in nodes}
            self._ranks = {k: 0 for k in nodes}
            self._sizes = {k: 1 for k in nodes}

    def unite(self, x, y):
        """
        x が属する木と y が属する木を併合
        :param x:
        :param y:
        :return:
        """
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return

        # rank が小さい方が下
        if self._ranks[x] > self._ranks[y]:
            # x が root
            self._parents[y] = x
            self._sizes[x] += self._sizes[y]
        else:
            # y が root
            self._parents[x] = y
            self._sizes[y] += self._sizes[x]
            if self._ranks[x] == self._ranks[y]:
                self._ranks[y] += 1

    def find(self, x):
        """
        x が属する木の root
        :param x:
        :return:
        """
        if self._parents[x] == x:
            return x
        self._parents[x] = self.find(self._parents[x])
        return self._parents[x]

    def size(self, x):
        """
        x が属する木のノード数
        :param x:
        :return:
        """
        return self._sizes[self.find(x)]


uf1 = UnionFind(size=N + 1)
for p, q in zip(P, Q):
    uf1.unite(p, q)
uf2 = UnionFind(size=N + 1)
for r, s in zip(R, S):
    uf2.unite(r, s)

counts = defaultdict(int)
for i in range(1, N + 1):
    counts[(uf1.find(i), uf2.find(i))] += 1

ans = []
for i in range(1, N + 1):
    ans.append(counts[(uf1.find(i), uf2.find(i))])
print(' '.join(map(str, ans)))

Submission status: Accepted

Solution code:
from collections import defaultdict
class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]

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

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

        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

N,K,L = map(int,input().split())
u1 = UnionFind(N)
u2 = UnionFind(N)
for _ in range(K):
    p,q = map(int,input().split())
    u1.union(p-1,q-1)
for _ in range(L):
    r,s = map(int,input().split())
    u2.union(r-1,s-1)

d = defaultdict(lambda:0)
for i in range(N):
    d[(u1.find(i),u2.find(i))] += 1

ans = []
for i in range(N):
    ans.append(str(d[(u1.find(i),u2.find(i))]))

ans = ' '.join(ans)
print(ans)

Submission status: Accepted

Solution code:
class UnionFind():
    def __init__(self, N):
        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]:
                self.rank[x] += 1
            elif self.rank[x] < self.rank[y]:
                x, y = y, x
            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]

from collections import defaultdict

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

uf1 = UnionFind(N)
for i in range(K):
    p, q = map(int, input().split())
    uf1.union(p-1, q-1)

uf2 = UnionFind(N)
for i in range(L):
    r, s = map(int, input().split())
    uf2.union(r-1, s-1)

c = defaultdict(int)
for i in range(N):
    c[(uf1.find(i), uf2.find(i))] += 1

for i in range(N):
    print(c[(uf1.find(i), uf2.find(i))], end = ' ', )

Submission status: Accepted

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

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

    def root(self, A):
        if self.parent[A] == A:
            return A
        self.parent[A] = self.root(self.parent[A]) #経路縮約
        return self.parent[A]

    def connect(self, A, B):
        A = self.root(A)
        B = self.root(B)
        self.parent[A] = B
        
uni1 = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    if uni1.root(p-1) != uni1.root(q-1):
        uni1.connect(p-1,q-1)

uni2 = UnionFind(N)
for _ in range(L):
    r, s = map(int, input().split())
    if uni2.root(r-1) != uni2.root(s-1):
        uni2.connect(r-1,s-1)

# print (uni1.parent)
# print (uni2.parent)

ans = dict()
key_list = []
for i in range(N): #各都市を検索
    root1 = uni1.root(i) #都市の親を探す
    root2 = uni2.root(i)
    key = str(root1) + '_' + str(root2) #2つの親を連結したものをkeyとする
    key_list.append(key) #リストにkeyを足しておく(=i番目の都市が属するグループとして前からメモ)
    if key in ans.keys(): #dict andに親の組を記録していく
        ans[key] += 1
    else:
        ans[key] = 1
    
for i in range(N):
    print (ans[key_list[i]], end = ' ') #i番目の都市の親の組はkeyで読み出せる
print ()






# for i in range(1, N+1):
#     ans = 0
#     for j in range(1, N+1):
#         # print (uni1.root(i), uni1.root(j), uni2.root(i), uni2.root(j))
#         if uni1.root(i) == uni1.root(j) and uni2.root(i) == uni2.root(j):
#             ans += 1
#     print (ans, end = ' ')
print ()

# print (uni1.parent)
# print (uni2.parent)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import Counter
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

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

P = [None] * K
Q = [None] * K
for i in range(K):
  P[i], Q[i] = map(int,input().split())

R = [None] * L
S = [None] * L
for i in range(L):
  R[i], S[i] = map(int,input().split())


g1 = csr_matrix(([1]*K,(P,Q)),(N+1,N+1))
g2 = csr_matrix(([1]*L,(R,S)),(N+1,N+1))

_,comp1 = connected_components(g1,directed = False,return_labels = True)
_,comp2 = connected_components(g2,directed = False,return_labels = True)

comp_pair = comp1.astype('int64') * (N+1) + comp2
c = Counter(comp_pair)

answer = [c[comp_pair[i]] for i in range(1,N+1)]
print(*answer)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import Counter
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

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

PQ = [[int(x) for x in input().split()] for _ in range(K)]
RS = [[int(x) for x in input().split()] for _ in range(L)]

P,Q = zip(*PQ)
R,S = zip(*RS)

g1 = csr_matrix(([1]*K,(P,Q)),(N+1,N+1))
g2 = csr_matrix(([1]*L,(R,S)),(N+1,N+1))

_,comp1 = connected_components(g1,directed = False,return_labels = True)
_,comp2 = connected_components(g2,directed = False,return_labels = True)

comp_pair = comp1.astype('int64') * (N+1) + comp2
c = Counter(comp_pair)

answer = [c[comp_pair[i]] for i in range(1,N+1)]
print(*answer)

Submission status: Accepted

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

debug = True
#debug = False

def dprint(*objects):
    if debug == True:
        print(*objects)

class UnionFind:

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

    def merge(self, i, j):
        rooti = self.findroot(i)
        rootj = self.findroot(j)
        self.parents[rooti] = rootj

    def issame(self, i, j):
        rooti = self.findroot(i)
        rootj = self.findroot(j)
        return rooti == rootj

    def findroot(self, i, followed_indices=None):

        if i == self.parents[i]:
            return i
        else:
            root = self.findroot(self.parents[i])
            self.parents[i] = root # 経路圧縮
            return root
    pass

def solve():
    # np.set_printoptions(suppress=True)
    # n = int(input())
    n, k, l = map(int, input().split())
    uf1 = UnionFind(n)
    uf2 = UnionFind(n)

    for ki in range(k):
        p, q = map(int, input().split())
        uf1.merge(p-1, q-1)

    for li in range(l):
        p, q = map(int, input().split())
        uf2.merge(p-1, q-1)

    ans = {}
    key_list = []
    for i in range(n):
        root1 = uf1.findroot(i)
        root2 = uf2.findroot(i)

        key = str(root1) + "_" + str(root2)
        key_list.append(key)

        if key in ans.keys():
            ans[key] += 1
        else:
            ans[key] = 1

    for i in range(n):
        print(ans[key_list[i]], end=' ')

solve()

Submission status: Accepted

Solution code:
import collections
import sys
input = sys.stdin.readline
n,k,l=map(int,input().split())

parD,parT=[-1]*n,[-1]*n
def findD(x):
  if parD[x]<0:
    return x
  else:
    parD[x]=findD(parD[x])
    return parD[x]
def uniteD(x,y):
  x=findD(x)
  y=findD(y)
  if x==y:
    return False
  else:
    if parD[x]>parD[y]:
      x,y=y,x
    parD[x]+=parD[y]
    parD[y]=x
    return True
def sameD(x,y):
  return findD(x)==findD(y)
def sizeD(x):
  return -parD[findD(x)]
def findT(x):
  if parT[x]<0:
    return x
  else:
    parT[x]=findT(parT[x])
    return parT[x]
def uniteT(x,y):
  x=findT(x)
  y=findT(y)
  if x==y:
    return False
  else:
    if parT[x]>parT[y]:
      x,y=y,x
    parT[x]+=parT[y]
    parT[y]=x
    return True
def sameT(x,y):
  return findT(x)==findT(y)
def sizeD(x):
  return -parT[findT(x)]


for i in range(k):
  p,q=map(int,input().split())
  uniteD(p-1,q-1)
for i in range(l):
  r,s=map(int,input().split())
  uniteT(r-1,s-1)
for i in range(n):
  findD(i)
  findT(i)
C=[]
for i in range(n):
  if parD[i]<0:
    parD[i]=i
  if parT[i]<0:
    parT[i]=i
Ans=[]
for i in range(n):
  Ans.append((parD[i],parT[i]))
ANS=collections.Counter(Ans)
for i in range(n):
  print(ANS[Ans[i]])

Submission status: Accepted

Solution code:
import copy

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

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

	def unite(self, a, b):
		ta = self.find(a)
		tb = self.find(b)
		if(ta != tb):
			self._parent[ta] = min(ta,tb)
			self._parent[tb] = self._parent[ta]
		
			
	def check(self, a, b):
		return self.find(a) == self.find(b)
		
if __name__ == '__main__':
	N,K,L = map(int, input().split())
	uf1 = UnionFind(N)
	for _ in range(K):
		p,q = map(int, input().split())
		uf1.unite(p-1,q-1)
	uf2 = UnionFind(N)
	for _ in range(L):
		s,r = map(int, input().split())
		uf2.unite(s-1,r-1)
	from collections import defaultdict
	d = defaultdict(int)
	for i in range(N):
		d[(uf1.find(i), uf2.find(i))] += 1
	ans = []
	for i in range(N):
		ans.append( str(d[(uf1.find(i), uf2.find(i))]) )
	print(' '.join(ans))

Submission status: Accepted

Solution code:
class UF():
  def __init__(self, N):
    self._parent=[n for n in range(0, N)]
    self._size=[1] * N

  def find_root(self, x):
    if self._parent[x]==x:return x
    self._parent[x]=self.find_root(self._parent[x])
    return self._parent[x]

  def unite(self, x, y):
    gx=self.find_root(x)
    gy=self.find_root(y)
    if gx==gy:return

    if self._size[gx]<self._size[gy]:
      self._parent[gx]=gy
      self._size[gy]+=self._size[gx]
    else:
      self._parent[gy]=gx
      self._size[gx]+=self._size[gy]

  def size(self, x):
    return self._size[self.find_root(x)]

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

  def groupnum(self):
    N=len(self._parent)
    ans=0
    for i in range(N):
      if self.find_root(i)==i:
        ans+=1
    return ans

from collections import defaultdict
n,k,l=map(int,input().split())
UF1=UF(n)
for i in range(k):
  p,q=map(int,input().split())
  UF1.unite(p-1,q-1)
UF2=UF(n)
for i in range(l):
  r,s=map(int,input().split())
  UF2.unite(r-1,s-1)
d=defaultdict(int)
for i in range(n):
  d[UF1.find_root(i),UF2.find_root(i)]+=1
ans=[]
for i in range(n):
  ans.append(str(d[UF1.find_root(i),UF2.find_root(i)]))
print(' '.join(ans))

Submission status: Accepted

Solution code:
#coding:utf-8
import sys
N,K,L=map(int,raw_input().split())

# https://www.kumilog.net/entry/union-find#Python%E3%81%A7%E5%AE%9F%E8%A3%85
class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

ufR=UnionFind(N+1)
ufT=UnionFind(N+1)
for i in range(K):
    p,q=map(int,sys.stdin.readline().split())
    ufR.union(p,q)
for i in range(L):
    p,q=map(int,sys.stdin.readline().split())
    ufT.union(p,q)    
from collections import defaultdict
R=defaultdict(set)
T=defaultdict(set)
for i in range(1,N+1):
    R[ufR.find(i)].add(i)
    T[ufT.find(i)].add(i)

P=defaultdict(int)
for i in range(1,N+1):
    P[ufR.find(i),ufT.find(i)]+=1

for i in range(1,N+1):
    print(P[ufR.find(i),ufT.find(i)])

Submission status: Accepted

Solution code:
#coding:utf-8
import sys
N,K,L=map(int,raw_input().split())

# https://www.kumilog.net/entry/union-find#Python%E3%81%A7%E5%AE%9F%E8%A3%85
class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

ufR=UnionFind(N+1)
ufT=UnionFind(N+1)
for i in range(K):
    p,q=map(int,sys.stdin.readline().split())
    ufR.union(p,q)
for i in range(L):
    p,q=map(int,sys.stdin.readline().split())
    ufT.union(p,q)    
from collections import defaultdict
R=defaultdict(set)
T=defaultdict(set)
for i in range(1,N+1):
    R[ufR.find(i)].add(i)
    T[ufT.find(i)].add(i)

ans=[0]*(N+1)
for i in range(1,N+1):
    if ans[i]!=0:continue
    r=R[ufR.find(i)]
    t=T[ufT.find(i)]
    if len(r)==0 or len(t)==0: continue
    s=r&t
    for c in s:
        ans[c]=str(len(s))
    r-=s
    t-=s

print(" ".join(ans[1:]))