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:
import sys
input = sys.stdin.readline
from collections import deque

def main():
    # 入力
    n, k, l = map(int, input().split())
    road_a = [None] * k
    road_b = [None] * k
    road = [[] for _ in range(n + 1)]
    train_a = [None] * l
    train_b = [None] * l
    train = [[] for _ in range(n + 1)]
    city_group_in_road = {e: -1 for e in range(1, n + 1)}
    city_group_in_train = {e: -1 for e in range(1, n + 1)}
    road_groups = {}
    train_groups = {}
    stack_road = deque()
    stack_train = deque()

    for i1 in range(k):
        road_a[i1], road_b[i1] = map(int, input().split())
        road[road_a[i1]].append(road_b[i1])
        road[road_b[i1]].append(road_a[i1])
    for i2 in range(l):
        train_a[i2], train_b[i2] = map(int, input().split())
        train[train_a[i2]].append(train_b[i2])
        train[train_b[i2]].append(train_a[i2])

    # 処理
    ## 道路
    group_num_road = 1
    for i_road in range(1, n + 1):
        if city_group_in_road[i_road] == -1 and road[i_road] != []:
            road_groups[group_num_road] = set()
            road_groups[group_num_road].add(i_road)
            city_group_in_road[i_road] = group_num_road
            stack_road += road[i_road]
            while stack_road:
                next = stack_road.popleft()
                if city_group_in_road[next] != -1:
                    continue
                road_groups[group_num_road].add(next)
                city_group_in_road[next] = group_num_road
                stack_road += road[next]
            group_num_road += 1


    ## 鉄道
    group_num_train = 1
    for i_train in range(1, n + 1):
        if city_group_in_train[i_train] == -1 and train[i_train] != [] and city_group_in_road[i_train] != -1:
            train_groups[group_num_train] = set()
            train_groups[group_num_train].add(i_train)
            city_group_in_train[i_train] = group_num_train
            stack_train += train[i_train]
            while stack_train:
                next = stack_train.popleft()
                if city_group_in_train[next] != -1:
                    continue
                train_groups[group_num_train].add(next)
                city_group_in_train[next] = group_num_train
                stack_train += train[next]
            group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = city_group_in_road[i]
        tg = city_group_in_train[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_groups[rg].intersection(train_groups[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def main():
    # 入力
    n, k, l = map(int, input().split())
    road_a = [None] * k
    road_b = [None] * k
    road = [[] for _ in range(n + 1)]
    train_a = [None] * l
    train_b = [None] * l
    train = [[] for _ in range(n + 1)]
    city_group_in_road = {e: -1 for e in range(1, n + 1)}
    city_group_in_train = {e: -1 for e in range(1, n + 1)}
    road_groups = {}
    train_groups = {}
    stack_road = deque()
    stack_train = deque()

    for i1 in range(k):
        road_a[i1], road_b[i1] = map(int, input().split())
        road[road_a[i1]].append(road_b[i1])
        road[road_b[i1]].append(road_a[i1])
    for i2 in range(l):
        train_a[i2], train_b[i2] = map(int, input().split())
        train[train_a[i2]].append(train_b[i2])
        train[train_b[i2]].append(train_a[i2])

    # 処理
    ## 道路
    group_num_road = 1
    for i_road in range(1, n + 1):
        if city_group_in_road[i_road] == -1 and road[i_road] != []:
            road_groups[group_num_road] = set()
            road_groups[group_num_road].add(i_road)
            city_group_in_road[i_road] = group_num_road
            stack_road += road[i_road]
            while stack_road:
                next = stack_road.popleft()
                if city_group_in_road[next] != -1:
                    continue
                road_groups[group_num_road].add(next)
                city_group_in_road[next] = group_num_road
                stack_road += road[next]
            group_num_road += 1


    ## 鉄道
    group_num_train = 1
    for i_train in range(1, n + 1):
        if city_group_in_train[i_train] == -1 and train[i_train] != []:
            train_groups[group_num_train] = set()
            train_groups[group_num_train].add(i_train)
            city_group_in_train[i_train] = group_num_train
            stack_train += train[i_train]
            while stack_train:
                next = stack_train.popleft()
                if city_group_in_train[next] != -1:
                    continue
                train_groups[group_num_train].add(next)
                city_group_in_train[next] = group_num_train
                stack_train += train[next]
            group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = city_group_in_road[i]
        tg = city_group_in_train[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_groups[rg].intersection(train_groups[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def main():
    # 入力
    n, k, l = map(int, input().split())
    road_a = [None] * k
    road_b = [None] * k
    road = [[] for _ in range(n + 1)]
    train_a = [None] * l
    train_b = [None] * l
    train = [[] for _ in range(n + 1)]
    city_group_in_road = {e: -1 for e in range(1, n + 1)}
    city_group_in_train = {e: -1 for e in range(1, n + 1)}
    road_groups = {}
    train_groups = {}
    stack_road = deque()
    stack_train = deque()

    for i1 in range(k):
        road_a[i1], road_b[i1] = map(int, input().split())
        road[road_a[i1]].append(road_b[i1])
        road[road_b[i1]].append(road_a[i1])
    for i2 in range(l):
        train_a[i2], train_b[i2] = map(int, input().split())
        train[train_a[i2]].append(train_b[i2])
        train[train_b[i2]].append(train_a[i2])

    # 処理
    ## 道路
    group_num_road = 1
    for i_road in range(1, n + 1):
        if city_group_in_road[i_road] == -1:
            road_groups[group_num_road] = set()
            road_groups[group_num_road].add(i_road)
            city_group_in_road[i_road] = group_num_road
            stack_road += road[i_road]
            while stack_road:
                next = stack_road.popleft()
                if city_group_in_road[next] != -1:
                    continue
                road_groups[group_num_road].add(next)
                city_group_in_road[next] = group_num_road
                stack_road += road[next]
            group_num_road += 1


    ## 鉄道
    group_num_train = 1
    for i_train in range(1, n + 1):
        if city_group_in_train[i_train] == -1:
            train_groups[group_num_train] = set()
            train_groups[group_num_train].add(i_train)
            city_group_in_train[i_train] = group_num_train
            stack_train += train[i_train]
            while stack_train:
                next = stack_train.popleft()
                if city_group_in_train[next] != -1:
                    continue
                train_groups[group_num_train].add(next)
                city_group_in_train[next] = group_num_train
                stack_train += train[next]
            group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = city_group_in_road[i]
        tg = city_group_in_train[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_groups[rg].intersection(train_groups[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def main():
    # 入力
    n, k, l = map(int, input().split())
    road = {e: [] for e in range(1, n + 1)}
    train = {e: [] for e in range(1, n + 1)}
    city_group_in_road = {e: -1 for e in range(1, n + 1)}
    city_group_in_train = {e: -1 for e in range(1, n + 1)}
    road_groups = {}
    train_groups = {}
    stack_road = deque()
    stack_train = deque()

    for _ in range(k):
        p, q = map(int, input().split())
        road[p].append(q)
        road[q].append(p)

    for _ in range(l):
        s, t = map(int, input().split())
        train[s].append(t)
        train[t].append(s)

    # 処理
    ## 道路
    group_num_road = 1
    for i_road in range(1, n + 1):
        if city_group_in_road[i_road] == -1:
            road_groups[group_num_road] = set()
            road_groups[group_num_road].add(i_road)
            city_group_in_road[i_road] = group_num_road
            stack_road += road[i_road]
            while stack_road:
                next = stack_road.popleft()
                if city_group_in_road[next] != -1:
                    continue
                road_groups[group_num_road].add(next)
                city_group_in_road[next] = group_num_road
                stack_road += road[next]
            group_num_road += 1
    

    ## 鉄道
    group_num_train = 1
    for i_train in range(1, n + 1):
        if city_group_in_train[i_train] == -1:
            train_groups[group_num_train] = set()
            train_groups[group_num_train].add(i_train)
            city_group_in_train[i_train] = group_num_train
            stack_train += train[i_train]
            while stack_train:
                next = stack_train.popleft()
                if city_group_in_train[next] != -1:
                    continue
                train_groups[group_num_train].add(next)
                city_group_in_train[next] = group_num_train
                stack_train += train[next]
            group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = city_group_in_road[i]
        tg = city_group_in_train[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_groups[rg].intersection(train_groups[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**6)
from collections import deque
from copy import deepcopy

road = {}
train = {}
node_seen_road = set()
node_seen_train = set()
road_belong_group = {}
train_belong_group = {}
road_group = {}
train_group = {}
group_num_road = 0
group_num_train = 0
city_without_road = set()

def dfs_road(t_node):
    global road_group, road_belong_group, node_seen_road
    road_belong_group[t_node] = group_num_road
    road_group[group_num_road].add(t_node)
    node_seen_road.add(t_node)
    next_nodes = set(road[t_node]) - node_seen_road
    if len(next_nodes) == 0:
        return
    else:
        for nextnr in next_nodes:
            dfs_road(nextnr)

def dfs_train(t_node):
    global node_seen_train, train_group, train_belong_group
    train_belong_group[t_node] = group_num_train
    train_group[group_num_train].add(t_node)
    node_seen_train.add(t_node)
    next_nodes = set(train[t_node]) - node_seen_train
    if len(next_nodes) == 0:
        return
    else:
        for nextnt in next_nodes:
            dfs_train(nextnt)


def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group, group_num_road, group_num_train, city_without_road
    # 入力
    n, k, l = map(int, input().split())
    #node_all = set([i for i in range(1, n + 1)])
    road = {e: [] for e in range(1, n + 1)}
    train = {e: [] for e in range(1, n + 1)}
    road_belong_group = {e: -1 for e in range(1, n + 1)}
    train_belong_group = {e: -1 for e in range(1, n + 1)}
    #city_list_forroad = deque([j for j in range(1, n + 1)])
    #city_list_fortrain = deepcopy(city_list_forroad)


    for _ in range(k):
        p, q = map(int, input().split())
        road[p].append(q)
        road[q].append(p)

    for _ in range(l):
        s, t = map(int, input().split())
        train[s].append(t)
        train[t].append(s)

    # 処理
    ## 道路

    group_num_road = 1
    for i_road in range(1, n + 1):
        if i_road in node_seen_road:
            continue
        if not road[i_road]:
            continue
        road_group[group_num_road] = set()
        dfs_road(i_road)
        group_num_road += 1
    #city_without_road = set([ci for ci in road_belong_group if road_belong_group[ci] == -1])

    ## 鉄道

    group_num_train = 1
    for i_train in range(1, n + 1):
        if i_train in node_seen_train or i_train not in node_seen_road:
            continue
        if not train[i_train]:
            continue
        train_group[group_num_train] = set()
        dfs_train(i_train)
        group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = road_belong_group[i]
        tg = train_belong_group[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_group[rg].intersection(train_group[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

road = {}
train = {}
node_seen_road = set()
node_seen_train = set()
road_belong_group = {}
train_belong_group = {}
road_group = {}
train_group = {}
group_num_road = 0
group_num_train = 0
city_without_road = set()

def dfs_road(t_node):
    global road_group, road_belong_group, node_seen_road
    road_belong_group[t_node] = group_num_road
    road_group[group_num_road].add(t_node)
    node_seen_road.add(t_node)
    next_nodes = set(road[t_node]) - node_seen_road
    if len(next_nodes) == 0:
        return
    else:
        for nextnr in next_nodes:
            dfs_road(nextnr)

def dfs_train(t_node):
    global node_seen_train, train_group, train_belong_group
    train_belong_group[t_node] = group_num_train
    train_group[group_num_train].add(t_node)
    node_seen_train.add(t_node)
    next_nodes = set(train[t_node]) - node_seen_train
    if len(next_nodes) == 0:
        return
    else:
        for nextnt in next_nodes:
            dfs_train(nextnt)


def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group, group_num_road, group_num_train, city_without_road
    # 入力
    n, k, l = map(int, input().split())
    #node_all = set([i for i in range(1, n + 1)])
    road = {e: [] for e in range(1, n + 1)}
    train = {e: [] for e in range(1, n + 1)}
    road_belong_group = {e: -1 for e in range(1, n + 1)}
    train_belong_group = {e: -1 for e in range(1, n + 1)}

    for _ in range(k):
        p, q = map(int, input().split())
        road[p].append(q)
        road[q].append(p)

    for _ in range(l):
        s, t = map(int, input().split())
        train[s].append(t)
        train[t].append(s)

    # 処理
    ## 道路

    group_num_road = 1
    for i_road in range(1, n + 1):
        if road_belong_group[i_road] != -1:
            continue
        if not road[i_road]:
            continue
        road_group[group_num_road] = set()
        dfs_road(i_road)
        group_num_road += 1
    #city_without_road = set([ci for ci in road_belong_group if road_belong_group[ci] == -1])

    ## 鉄道

    group_num_train = 1
    for i_train in range(1, n + 1):
        if train_belong_group[i_train] != -1 or i_train not in node_seen_road:
            continue
        if not train[i_train]:
            continue
        train_group[group_num_train] = set()
        dfs_train(i_train)
        group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = road_belong_group[i]
        tg = train_belong_group[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_group[rg].intersection(train_group[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

road = {}
train = {}
node_seen = set()
road_belong_group = {}
train_belong_group = {}
road_group = {}
train_group = {}
group_num_road = 0
group_num_train = 0
city_without_road = set()

def dfs_road(t_node):
    global road_group, road_belong_group, node_seen
    road_belong_group[t_node] = group_num_road
    road_group[group_num_road].add(t_node)
    node_seen.add(t_node)
    next_nodes = set(road[t_node]) - node_seen
    if len(next_nodes) == 0:
        return
    else:
        for nextnr in next_nodes:
            dfs_road(nextnr)

def dfs_train(t_node):
    global node_seen, train_group, train_belong_group
    train_belong_group[t_node] = group_num_train
    train_group[group_num_train].add(t_node)
    node_seen.add(t_node)
    next_nodes = set(train[t_node]) - node_seen
    if len(next_nodes) == 0:
        return
    else:
        for nextnt in next_nodes:
            dfs_train(nextnt)


def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group, group_num_road, group_num_train, city_without_road
    # 入力
    n, k, l = map(int, input().split())
    #node_all = set([i for i in range(1, n + 1)])
    road = {e: [] for e in range(1, n + 1)}
    train = {e: [] for e in range(1, n + 1)}
    road_belong_group = {e: -1 for e in range(1, n + 1)}
    train_belong_group = {e: -1 for e in range(1, n + 1)}

    for _ in range(k):
        p, q = map(int, input().split())
        road[p].append(q)
        road[q].append(p)

    for _ in range(l):
        s, t = map(int, input().split())
        train[s].append(t)
        train[t].append(s)

    # 処理
    ## 道路

    group_num_road = 1
    for i_road in range(1, n + 1):
        if road_belong_group[i_road] != -1:
            continue
        if not road[i_road]:
            continue
        road_group[group_num_road] = set()
        dfs_road(i_road)
        group_num_road += 1
    city_without_road = set([ci for ci in road_belong_group if road_belong_group[ci] == -1])

    ## 鉄道
    node_seen = set([])
    group_num_train = 1
    for i_train in range(1, n + 1):
        if train_belong_group[i_train] != -1 or road_belong_group[i_train] == -1:
            continue
        if not train[i_train]:
            continue
        train_group[group_num_train] = set()
        dfs_train(i_train)
        group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = road_belong_group[i]
        tg = train_belong_group[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_group[rg].intersection(train_group[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

road = {}
train = {}
node_seen = set()
road_belong_group = {}
train_belong_group = {}
road_group = {}
train_group = {}
group_num_road = 0
group_num_train = 0

def dfs_road(t_node):
    global road_group, road_belong_group, node_seen
    road_belong_group[t_node] = group_num_road
    road_group[group_num_road].add(t_node)
    node_seen.add(t_node)
    next_nodes = set(road[t_node]) - node_seen
    if len(next_nodes) == 0:
        return
    else:
        for nextnr in next_nodes:
            dfs_road(nextnr)

def dfs_train(t_node):
    global node_seen, train_group, train_belong_group
    train_belong_group[t_node] = group_num_train
    train_group[group_num_train].add(t_node)
    node_seen.add(t_node)
    next_nodes = set(train[t_node]) - node_seen
    if len(next_nodes) == 0:
        return
    else:
        for nextnt in next_nodes:
            dfs_train(nextnt)


def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group, group_num_road, group_num_train
    # 入力
    n, k, l = map(int, input().split())
    #node_all = set([i for i in range(1, n + 1)])
    road = {e: [] for e in range(1, n + 1)}
    train = {e: [] for e in range(1, n + 1)}
    road_belong_group = {e: -1 for e in range(1, n + 1)}
    train_belong_group = {e: -1 for e in range(1, n + 1)}

    for _ in range(k):
        p, q = map(int, input().split())
        road[p].append(q)
        road[q].append(p)

    for _ in range(l):
        s, t = map(int, input().split())
        train[s].append(t)
        train[t].append(s)

    # 処理
    ## 道路

    group_num_road = 1
    for i_road in range(1, n + 1):
        if road_belong_group[i_road] != -1:
            continue
        if not road[i_road]:
            continue
        road_group[group_num_road] = set()
        dfs_road(i_road)
        group_num_road += 1

    ## 鉄道
    node_seen = set([])
    group_num_train = 1
    for i_train in range(1, n + 1):
        if train_belong_group[i_train] != -1:
            continue
        if not train[i_train]:
            continue
        train_group[group_num_train] = set()
        dfs_train(i_train)
        group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        rg = road_belong_group[i]
        tg = train_belong_group[i]
        if rg == -1 or tg == -1:
            print(1, end= ' ')
        else:
            linked_city = len(road_group[rg].intersection(train_group[tg]))
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def road_find(a):
    if Road[a] < 0:
        return a
    else:
        return road_find(Road[a])


def train_find(a):
    if Train[a] < 0:
        return a
    else:
        return train_find(Train[a])


def road_union(a, b):
    ag = road_find(a)
    bg = road_find(b)
    if ag == bg:
        return
    if Road[ag] > Road[bg]:
        ag, bg = bg, ag
    Road[ag] += Road[bg]
    Road[bg] = ag
    return


def train_union(a, b):
    ag = train_find(a)
    bg = train_find(b)
    if ag == bg:
        return
    if Train[ag] > Train[bg]:
        ag, bg = bg, ag
    Train[ag] += Train[bg]
    Train[bg] = ag
    return


N, K, L = map(int, input().split())
Road = [-1] * N
Train = [-1] * N
RoadG = [[] for _ in range(N)]
TrainG = [[] for _ in range(N)]

for road in range(K):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    road_union(p, q)
for i in range(N):
    RoadG[road_find(i)].append(i)

for train in range(L):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    train_union(p, q)
for i in range(N):
    TrainG[train_find(i)].append(i)


for i in range(N):
    i_road_g = road_find(i)
    i_train_g = train_find(i)
    print(len(set(TrainG[i_train_g]) & set(RoadG[i_road_g])), end=' ')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2000000)

class UnionFind():
    def __init__(self,n):
        self.n=n
        self.parents = [i for i in range(n+1)]
        self.size = [1]*(n+1)
    def find(self,x):
        if self.parents[x]==x:
            return x
        else:
            self.parents[x]=self.find(self.parents[x])
            return self.parents[x]
    def unite(self,x,y):
        xRoot = self.find(x)
        yRoot = self.find(y)
        if xRoot == yRoot:
            return
        if self.size[xRoot]>self.size[yRoot]:
            self.parents[yRoot] = xRoot
        else:
            self.parents[xRoot] = yRoot
            if self.size[xRoot] == self.size[yRoot]:
                self.size[yRoot]+=1
N,K,L = map(int,input().split())
roadTree = UnionFind(N)
railTree = UnionFind(N)
for _ in range(K):
    p,q = map(int,input().split())
    roadTree.unite(p,q)
for _ in range(L):
    p,q = map(int,input().split())
    railTree.unite(p,q)

roadGroup = {}
for i in range(1,N+1):
    p = roadTree.find(i)
    if p not in roadGroup:
        roadGroup[p] = [i]
    else:
        roadGroup[p].append(i)

railGroupNum = {}
for i in range(1,N+1):
    p = railTree.find(i)
    railGroupNum[i]=p

ans = [1]*(N)
for p,children in roadGroup.items():
    for i in range(len(children)):
        c1 = children[i]
        for j in range(i+1,len(children)):
            c2 = children[j]
            if railGroupNum[c1] == railGroupNum[c2]:
                ans[c1-1]+=1
                ans[c2-1]+=1
            
print(" ".join([str(a) for a in ans]))

Submission status: Time Limit Exceeded

Solution code:
n,k,l=map(int,input().split())
road=[list(map(int,input().split())) for i in range(k)]
train=[list(map(int,input().split())) for i in range(l)]

city1=[[i for i in range(n)]]
city2=[[i for i in range(n)]]
rank1=[0 for i in range(n)]
rank2=[0 for i in range(n)]
s1=[{i} for i in range(n)]
s2=[{i} for i in range(n)]
city1.append(rank1)
city1.append(s1)
city2.append(rank2)
city2.append(s2)
def find(c,x,y):
  return root(c,x)==root(c,y)
def root(c,x):
  if x==c[0][x]:
    return x
  else:
    return root(c,c[0][x])
def union(c,x,y):
  if find(c,x,y):
    return
  else:
    rx=root(c,x)
    ry=root(c,y)
    if c[1][x]>c[1][y]:
      c[0][y]=rx
      c[2][rx]=c[2][rx]|c[2][ry]
    elif c[1][y]>c[1][x]:
      c[0][x]=ry
      c[2][ry]=c[2][rx]|c[2][ry]
    else:
      c[0][x]=ry
      c[1][x]+=1
      c[2][ry]=c[2][rx]|c[2][ry]
for i in range(k):
  union(city1,road[i][0]-1,road[i][1]-1)
for i in range(l):
  union(city2,train[i][0]-1,train[i][1]-1)
root1=[root(city1,i) for i in range(n)]
root2=[root(city2,i) for i in range(n)]
for i in range(n):
  ans=len(city1[2][root1[i]] & city2[2][root2[i]])
  if i==n:
    print(ans)
  else:
    print(ans,end=' ')

Submission status: Time Limit Exceeded

Solution code:
n,k,l=map(int,input().split())
road=[list(map(int,input().split())) for i in range(k)]
train=[list(map(int,input().split())) for i in range(l)]

city1=[[i for i in range(n)]]
city2=[[i for i in range(n)]]
rank1=[0 for i in range(n)]
rank2=[0 for i in range(n)]
s1=[{i} for i in range(n)]
s2=[{i} for i in range(n)]
city1.append(rank1)
city1.append(s1)
city2.append(rank2)
city2.append(s2)
def find(c,x,y):
  return root(c,x)==root(c,y)
def root(c,x):
  if x==c[0][x]:
    return x
  else:
    return root(c,c[0][x])
def union(c,x,y):
  if find(c,x,y):
    return
  else:
    rx=root(c,x)
    ry=root(c,y)
    if c[1][x]>c[1][y]:
      c[0][y]=rx
      c[2][rx]=c[2][rx]|c[2][ry]
    elif c[1][y]>c[1][x]:
      c[0][x]=ry
      c[2][ry]=c[2][rx]|c[2][ry]
    else:
      c[0][x]=ry
      c[1][x]+=1
      c[2][ry]=c[2][rx]|c[2][ry]

for i in range(k):
  union(city1,road[i][0]-1,road[i][1]-1)
for i in range(l):
  union(city2,train[i][0]-1,train[i][1]-1)
ans=[0 for i in range(n)]
for i in range(n):
  ans[i]=len(city1[2][root(city1,i)] & city2[2][root(city2,i)])
  if i==n:
    print(ans[i])
  else:
    print(ans[i],end=' ')

Submission status: Time Limit Exceeded

Solution code:

[N, K, L] = [int(x) for x in input().rstrip().split()]
P = []
Q = []
R = []
S = []
for i in range(K):
    [p,q] = [int(x) for x in input().rstrip().split()]
    P.append(p-1)
    Q.append(q-1)

for i in range(L):
    [r,s] = [int(x) for x in input().rstrip().split()]
    R.append(r-1)
    S.append(s-1)

road_parent = [i for i in range(N)]
train_parent = [i for i in range(N)]

def find_root(i,parent):
    path_element = []
    while(True):
        if parent[i] == i:
            #その途中の要素の親も変える
            for j in range(len(path_element)):
                parent[path_element[j]] = i
            return i
        else:
            path_element.append(i)
            i = parent[i]

def merge_tree(i,j,parent): #iとjが所属する木を合成する
    #最初にiとjが同じ気に木していないかをチェックする
    i_root = find_root(i,parent)
    j_root = find_root(j,parent)
    if j_root == i_root:
        #同じだったら何もしない
        return
    else:
        #違う場合にはjの根をiの根に繋ぎ変える
        parent[j_root] = i_root
        return


#まずは道路をつないで、union treeを作る
for i in range(K):
    merge_tree(P[i],Q[i],road_parent)

for i in range(L):
    merge_tree(R[i],S[i],train_parent)

root_map ={}
for i in range(N):
    find_root(i, road_parent)
    find_root(i, train_parent)
for i in range(N):
    temp = (road_parent[i],train_parent[i])
    if temp in root_map.keys():
        root_map[temp].append(i)
    else:
        root_map[temp] = [i]
for i in range(N):
    temp = (road_parent[i],train_parent[i])
    print(len(root_map[temp]))