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: Time Limit Exceeded

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


class UnionFindLabel(UnionFind):
    def __init__(self, labels):
        assert len(labels) == len(set(labels))

        self.n = len(labels)
        self.parents = [-1] * self.n
        self.d = {x: i for i, x in enumerate(labels)}
        self.d_inv = {i: x for i, x in enumerate(labels)}

    def find_label(self, x):
        return self.d_inv[super().find(self.d[x])]

    def union(self, x, y):
        super().union(self.d[x], self.d[y])

    def size(self, x):
        return super().size(self.d[x])

    def same(self, x, y):
        return super().same(self.d[x], self.d[y])

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

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

def MAP(): return map(int, input().split())
def ZIP(n): return zip(*(MAP() for _ in range(n)))

N, K, L = list(map(int, input().split()))
uf_road = UnionFindLabel(range(1, N + 1))
uf_train = UnionFindLabel(range(1, N + 1))

for i in range(K):
    node1, node2 = list(map(int, input().split()))
    uf_road.union(node1, node2)

for i in range(L):
    node1, node2 = list(map(int, input().split()))
    uf_train.union(node1, node2)

ans = [0] * N
ans = [len(set(uf_road.members(i)) & set(uf_train.members(i))) for i in range(1, N + 1)]
print(*ans)

Submission status: Time Limit Exceeded

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


class UnionFindLabel(UnionFind):
    def __init__(self, labels):
        assert len(labels) == len(set(labels))

        self.n = len(labels)
        self.parents = [-1] * self.n
        self.d = {x: i for i, x in enumerate(labels)}
        self.d_inv = {i: x for i, x in enumerate(labels)}

    def find_label(self, x):
        return self.d_inv[super().find(self.d[x])]

    def union(self, x, y):
        super().union(self.d[x], self.d[y])

    def size(self, x):
        return super().size(self.d[x])

    def same(self, x, y):
        return super().same(self.d[x], self.d[y])

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

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

def MAP(): return map(int, input().split())
def ZIP(n): return zip(*(MAP() for _ in range(n)))

N, K, L = list(map(int, input().split()))
uf_road = UnionFindLabel(range(1, N + 1))
uf_train = UnionFindLabel(range(1, N + 1))

for i in range(K):
    node1, node2 = list(map(int, input().split()))
    uf_road.union(node1, node2)

for i in range(L):
    node1, node2 = list(map(int, input().split()))
    uf_train.union(node1, node2)

ans = [1] * N
for i in range(1, N + 1):
    cands = set()
    for m in uf_road.members(i):
        if i != m:
            cands.add(m)
    for m in uf_train.members(i):
        if i != m:
            if m in cands:
                ans[i - 1] += 1
print(*ans)

Submission status: Time Limit Exceeded

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


class UnionFindLabel(UnionFind):
    def __init__(self, labels):
        assert len(labels) == len(set(labels))

        self.n = len(labels)
        self.parents = [-1] * self.n
        self.d = {x: i for i, x in enumerate(labels)}
        self.d_inv = {i: x for i, x in enumerate(labels)}

    def find_label(self, x):
        return self.d_inv[super().find(self.d[x])]

    def union(self, x, y):
        super().union(self.d[x], self.d[y])

    def size(self, x):
        return super().size(self.d[x])

    def same(self, x, y):
        return super().same(self.d[x], self.d[y])

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

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

def MAP(): return map(int, input().split())
def ZIP(n): return zip(*(MAP() for _ in range(n)))

N, K, L = list(map(int, input().split()))
uf_road = UnionFindLabel(range(1, N + 1))
uf_train = UnionFindLabel(range(1, N + 1))

for i in range(K):
    node1, node2 = list(map(int, input().split()))
    uf_road.union(node1, node2)

for i in range(L):
    node1, node2 = list(map(int, input().split()))
    uf_train.union(node1, node2)

res_dict = {}
ans = [1] * N
for i in range(1, N + 1):
    cands = set()
    for m in uf_road.members(i):
        if i != m:
            cands.add(m)
    for m in uf_train.members(i):
        if i != m:
            if m in cands:
                ans[i - 1] += 1
print(*ans)

Submission status: Time Limit Exceeded

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


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

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

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

        if x == y:
            return

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

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

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

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

    def 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())
uf_k = UnionFind(n)
uf_l = UnionFind(n)
ans = [0] * n
for i in range(k):
    p, q = map(int, input().split())
    uf_k.union(p - 1, q - 1)
for i in range(l):
    r, s = map(int, input().split())
    uf_l.union(r - 1, s - 1)
for i in range(n):
    k_member = uf_k.members(i)
    l_member = uf_l.members(i)
    all_member = k_member + l_member
    cnt = len(all_member)
    check = len(set(all_member))
    if cnt == check:
        ans[i] = 0
    elif cnt - 1 == check:
        ans[i] = 1
    else:
        ans[i] = 2
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from io import StringIO
import unittest

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

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k,l=map(int, readline().strip().split())

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

    for _ in range(k):
        a,b=map(int, readline().strip().split())
        uf1.Unite(a,b)
    for _ in range(l):
        a,b=map(int, readline().strip().split())
        uf2.Unite(a,b)
    
    d={}
    for i in range(1,n+1):
        root=uf1.Find_Root(i)
        if root in d:
            d[root].append(i)
        else:
            d[root]=[i]

    d2={}
    for i in range(1,n+1):
        root=uf2.Find_Root(i)
        if root in d2:
            d2[root].append(i)
        else:
            d2[root]=[i]

    ans=[""]*(n+2)

    for key in d.keys():
        lend=len(d[key])
        if lend==1:
            ans[d[key][0]]="1"
        else:
            for i in range(len(d[key])):
                if ans[d[key][i]]!="":
                    continue
                root2=uf2.Find_Root(d[key][i])
                and12 = set(d[key]) & set(d2[root2])
                lenand=str(len(and12))
                for a in and12:
                    ans[a]=lenand

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

    #uf1=uf.Unite(a,b)
    #n,m,k=list(map(int, readline().strip().split()))
    #arr=list(map(int, readline().strip().split()))
    #n=int(readline().strip())

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまでコピぺえ 
### ----------------

Submission status: Time Limit Exceeded

Solution code:
import sys
from io import StringIO
import unittest

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

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k,l=map(int, readline().strip().split())

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

    for _ in range(k):
        a,b=map(int, readline().strip().split())
        uf1.Unite(a,b)
    for _ in range(l):
        a,b=map(int, readline().strip().split())
        uf2.Unite(a,b)
    
    d={}
    for i in range(1,n+1):
        root=uf1.Find_Root(i)
        if root in d:
            d[root].append(i)
        else:
            d[root]=[i]

    d2={}
    for i in range(1,n+1):
        root=uf2.Find_Root(i)
        if root in d2:
            d2[root].append(i)
        else:
            d2[root]=[i]

    ans=[""]*(n+2)

    for key in d.keys():
        lend=len(d[key])
        if lend==1:
            ans[d[key][0]]="1"
        else:
            for i in range(len(d[key])):
                root2=uf2.Find_Root(d[key][i])
                and12 = set(d[key]) & set(d2[root2])
                lenand=str(len(and12))
                for a in and12:
                    ans[a]=lenand

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

    #uf1=uf.Unite(a,b)
    #n,m,k=list(map(int, readline().strip().split()))
    #arr=list(map(int, readline().strip().split()))
    #n=int(readline().strip())

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまでコピぺえ 
### ----------------

Submission status: Time Limit Exceeded

Solution code:

import sys
from io import StringIO
import unittest

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

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k,l=map(int, readline().strip().split())

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

    for _ in range(k):
        a,b=map(int, readline().strip().split())
        uf1.Unite(a,b)
    for _ in range(l):
        a,b=map(int, readline().strip().split())
        uf2.Unite(a,b)
    
    d={}
    for i in range(1,n+1):
        root=uf1.Find_Root(i)
        if root in d:
            d[root].append(i)
        else:
            d[root]=[i]

    ans=[""]*(n+2)

    for key in d.keys():
        lend=len(d[key])
        if lend==1:
            ans[d[key][0]]="1"
        else:
            for i in range(0,lend):
                if ans[d[key][i]] != "":
                    continue
                tmp=[d[key][i]]
                for j in range(0,len(d[key])):
                    if i==j:
                        continue
                    if uf2.isSameGroup(d[key][i],d[key][j]):
                        tmp.append(d[key][j])
                tmplen=len(tmp)
                for t in tmp:
                    ans[t]=str(tmplen)

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

    #uf1=uf.Unite(a,b)
    #n,m,k=list(map(int, readline().strip().split()))
    #arr=list(map(int, readline().strip().split()))
    #n=int(readline().strip())

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまでコピぺえ 
### ----------------

Submission status: Time Limit Exceeded

Solution code:
import sys
from io import StringIO
import unittest

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

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k,l=map(int, readline().strip().split())

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

    for _ in range(k):
        a,b=map(int, readline().strip().split())
        uf1.Unite(a,b)
    for _ in range(l):
        a,b=map(int, readline().strip().split())
        uf2.Unite(a,b)
    
    d={}
    for i in range(1,n+1):
        root=uf1.Find_Root(i)
        if root in d:
            d[root].append(i)
        else:
            d[root]=[i]

    ans=[0]*(n+2)

    for key in d.keys():
        lend=len(d[key])
        if lend==1:
            ans[d[key][0]]=1
        else:
            for i in range(0,lend):
                if ans[d[key][i]]>0:
                    continue
                tmp=[d[key][i]]
                for j in range(0,len(d[key])):
                    if i==j:
                        continue
                    if uf2.isSameGroup(d[key][i],d[key][j]):
                        tmp.append(d[key][j])
                tmplen=len(tmp)
                for t in tmp:
                    ans[t]=tmplen

    for i in range(1,n+1):
        if i<n:
            print(str(ans[i])+" ",end="")
        else:
            print(str(ans[i]))
    #uf1=uf.Unite(a,b)
    #n,m,k=list(map(int, readline().strip().split()))
    #arr=list(map(int, readline().strip().split()))
    #n=int(readline().strip())

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまでコピぺえ

Submission status: Time Limit Exceeded

Solution code:

import sys
from io import StringIO
import unittest

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

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k,l=map(int, readline().strip().split())

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

    for _ in range(k):
        a,b=map(int, readline().strip().split())
        uf1.Unite(a,b)
    for _ in range(l):
        a,b=map(int, readline().strip().split())
        uf2.Unite(a,b)
    
    d={}
    for i in range(1,n+1):
        root=uf1.Find_Root(i)
        if root in d:
            d[root].append(i)
        else:
            d[root]=[i]

    ans=[0]*(n+2)

    for key in d.keys():
        if len(d[key])==1:
            ans[d[key][0]]=1
        else:
            for i in range(0,len(d[key])):
                if ans[d[key][i]]>0:
                    continue
                tmp=[d[key][i]]
                for j in range(0,len(d[key])):
                    if i==j:
                        continue
                    if uf2.isSameGroup(d[key][i],d[key][j]):
                        tmp.append(d[key][j])
                for t in tmp:
                    ans[t]=len(tmp)

    for i in range(1,n+1):
        if i<n:
            print(str(ans[i])+" ",end="")
        else:
            print(str(ans[i]))
    #uf1=uf.Unite(a,b)
    #n,m,k=list(map(int, readline().strip().split()))
    #arr=list(map(int, readline().strip().split()))
    #n=int(readline().strip())

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

Submission status: Time Limit Exceeded

Solution code:
import sys
from io import StringIO
import unittest

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

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k,l=map(int, readline().strip().split())

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

    for _ in range(k):
        a,b=map(int, readline().strip().split())
        uf1.Unite(a,b)
    for _ in range(l):
        a,b=map(int, readline().strip().split())
        uf2.Unite(a,b)
    
    d={}
    for i in range(1,n+1):
        root=uf1.Find_Root(i)
        if root in d:
            d[root].append(i)
        else:
            d[root]=[i]

    ans=[0]*(n+2)

    for key in d.keys():
        if len(d[key])==1:
            ans[d[key][0]]=1
        else:
            for i in range(0,len(d[key])):
                if ans[d[key][i]]>0:
                    continue
                tmp=[d[key][i]]
                for j in range(0,len(d[key])):
                    if i==j:
                        continue
                    if uf2.isSameGroup(d[key][i],d[key][j]):
                        tmp.append(d[key][j])
                for t in tmp:
                    ans[t]=len(tmp)

    for i in range(1,n+1):
        if i<n:
            print(str(ans[i])+" ",end="")
        else:
            print(str(ans[i]))
    #uf1=uf.Unite(a,b)
    #n,m,k=list(map(int, readline().strip().split()))
    #arr=list(map(int, readline().strip().split()))
    #n=int(readline().strip())

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(4100000)
input = sys.stdin.readline

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

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

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

        if x == y:
            return

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

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

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

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

    def 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,input().split())
    road = UnionFind(N)
    train = UnionFind(N)

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

    for k in range(L):
        r, s = map(int,input().split())
        r -= 1
        s -= 1
        train.union(r,s)

    ans = [0]*N
    for k in range(N):
        if ans[k] != 0:
            pass
        else:
            t = set(road.members(k)) & set(train.members(k))
            for e in t:
                ans[e] = len(t)
    print(*ans)
if __name__ == '__main__':
    main()