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: Runtime Error

Solution code:
import collections
N, K, L = map(int, input().split())
city = [{"road":{"Connected":[],"set":-1,"seen":False},
         "rail":{"Connected":[],"set":-1,"seen":False}} for i in range(N)]

def dfs(graph, v, way, num): #深さ優先探索
    graph[v][way]["seen"] = True
    graph[v][way]["set"] = num
    for next_v in graph[v][way]["Connected"]:
        if graph[next_v][way]["seen"]:
            continue
        dfs(graph, next_v, way, num)

for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["road"]["Connected"].append(q-1)
    city[q-1]["road"]["Connected"].append(p-1)
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["rail"]["Connected"].append(s-1)
    city[s-1]["rail"]["Connected"].append(r-1)
for X in ["road", "rail"]: #連結成分に分解
    set_index = 0
    for v in range(N):
        if city[v][X]["seen"]:
            continue
        dfs(city, v, X, set_index)
        set_index += 1
List = [(x["road"]["set"],x["rail"]["set"]) for x in city]
counter = collections.Counter(List)
for A in List:
    print(counter[A],end=" ")

Submission status: Runtime Error

Solution code:
import collections
N, K, L = map(int, input().split())
city = [{"road":{"Connected":[i],"set":-1,"seen":False},
         "rail":{"Connected":[i],"set":-1,"seen":False}} for i in range(N)]
def dfs(graph, v, way, num):
    graph[v][way]["seen"] = True
    graph[v][way]["set"] = num
    for next_v in graph[v][way]["Connected"]:
        if graph[next_v][way]["seen"]:
            continue
        dfs(graph, next_v, way, num)

for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["road"]["Connected"].append(q-1)
    city[q-1]["road"]["Connected"].append(p-1)
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["rail"]["Connected"].append(s-1)
    city[s-1]["rail"]["Connected"].append(r-1)
for X in ["road", "rail"]:
    count = 0
    for v in range(N):
        if city[v][X]["seen"]:
            continue
        dfs(city, v, X, count)
        count += 1
List = [(x["road"]["set"],x["rail"]["set"]) for x in city]
counter = collections.Counter(List)
for A in List:
    print(counter[A],end=" ")

Submission status: Runtime Error

Solution code:
import collections
N, K, L = map(int, input().split())
city = [{"road":{"Connected":[i],"group":-1,"seen":False},
         "rail":{"Connected":[i],"group":-1,"seen":False}} for i in range(N)]
def dfs(graph, v, way, num):
    graph[v][way]["seen"] = True
    graph[v][way]["group"] = num
    for next_v in graph[v][way]["Connected"]:
        if graph[next_v][way]["seen"]:
            continue
        dfs(graph, next_v, way, num)

for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["road"]["Connected"].append(q-1)
    city[q-1]["road"]["Connected"].append(p-1)
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["rail"]["Connected"].append(s-1)
    city[s-1]["rail"]["Connected"].append(r-1)
for X in ["road", "rail"]:
    count = 0
    for v in range(N):
        if city[v][X]["seen"]:
            continue
        dfs(city, v, X, count)
        count += 1
List = [(city[i]["road"]["group"],city[i]["rail"]["group"]) for i in range(N)]
counter = collections.Counter(List)
for A in List:
    print(counter[A],end=" ")

Submission status: Runtime Error

Solution code:
import collections
N, K, L = map(int, input().split())
city = [{"road":{"Connected":[i],"seen":-1}, "rail":{"Connected":[i],"seen":-1}} for i in range(N)]
def dfs(graph, v, way, num):
    graph[v][way]["seen"] = num
    for next_v in graph[v][way]["Connected"]:
        if graph[next_v][way]["seen"] >= 0:
            continue
        dfs(graph, next_v, way, num)

for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["road"]["Connected"].append(q-1)
    city[q-1]["road"]["Connected"].append(p-1)
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["rail"]["Connected"].append(s-1)
    city[s-1]["rail"]["Connected"].append(r-1)
for X in ["road", "rail"]:
    count = 0
    for v in range(N):
        if city[v][X]["seen"] >= 0:
            continue
        dfs(city, v, X, count)
        count += 1
List = [(city[i]["road"]["seen"],city[i]["rail"]["seen"]) for i in range(N)]
counter = collections.Counter(List)
for i in range(N):
    print(counter[(city[i]["road"]["seen"],city[i]["rail"]["seen"])],end=" ")

Submission status: Runtime Error

Solution code:
N, K, L = map(int, input().split())
city = [{"road":{"Connected":[i],"seen":False}, "rail":{"Connected":[i],"seen":False}} for i in range(N)]
Connected_Components = {"road":list(),"rail":list()}
def dfs(graph, v, way, List):
    graph[v][way]["seen"] = True
    List.append(v)
    for next_v in graph[v][way]["Connected"]:
        if graph[next_v][way]["seen"] == True:
            continue
        dfs(graph, next_v, way, List)

for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["road"]["Connected"].append(q-1)
    city[q-1]["road"]["Connected"].append(p-1)
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["rail"]["Connected"].append(s-1)
    city[s-1]["rail"]["Connected"].append(r-1)
for X in ["road", "rail"]:
    count = 0
    for v in range(N):
        if city[v][X]["seen"] == True:
            continue
        Connected_Components[X].append(list())
        dfs(city, v, X, Connected_Components[X][count])
        
        for i in Connected_Components[X][count]:
            city[i][X]["Connected"] = Connected_Components[X][count]
        count += 1
for v in range(N):
    print(len(set(city[v]["road"]["Connected"])&set(city[v]["rail"]["Connected"])), end=" ")

Submission status: Runtime Error

Solution code:
N, K, L = map(int, input().split())
city = [1 for i in range(N)]
setA = set()
setB = set()
for i in range(K):
    X = set(int(x)-1 for x in input().split())
    for A in setA:
        if A & X != set():
            A = A | X
    else:
        setA.add(X)
for i in range(L):
    Y = set(int(y)-1 for y in input().split())
    for B in setB:
        if B & Y != set():
            B = B | Y
    else:
        setB.add(Y)
for A in setA:
    for B in setB:
        for i in A & B:
            city[i] = len(A&B)
for i in range(N):
    print(city[i], end=" ")

Submission status: Runtime Error

Solution code:
def dfs(now,vis,e,j,el):
  vis+=[now]
  e[now]=j
  res=set([now])
  for to in el[now]:
    if to in vis:continue
    res=res|dfs(to,vis[:],e,j,el)
    e[to]=j
  return res
n,k,l=map(int,input().split())
el=[set() for _ in range(n+1)]
et=[set() for _ in range(n+1)]
ela=[set() for _ in range(n+1)]
eta=[set() for _ in range(n+1)]
eml=[0]*(n+1)
emt=[0]*(n+1)
ans=[0]*(n+1)
for _ in range(k):
  p,q=map(int,input().split())
  el[p].add(q)
  el[q].add(p)
j=0
for i in range(n+1):
  if eml[i]:continue
  ela[j]=dfs(i,[],eml,j,el)
  j+=1
for _ in range(l):
  p,q=map(int,input().split())
  et[p].add(q)
  et[q].add(p)
j=0
for i in range(n+1):
  if emt[i]:continue
  eta[j]=dfs(i,[],emt,j,et)
  j+=1
for i in range(n+1):
  ans[i]=len(eta[emt[i]]&ela[eml[i]])
print(*ans[1:])

Submission status: Runtime Error

Solution code:
import collections

NO_OF_DIMENSIONS = 2
no_of_edges_by_dim = [0] * NO_OF_DIMENSIONS
n, no_of_edges_by_dim[0], no_of_edges_by_dim[1] = (int(x) for x in input().split())

graph_by_dimension = [[[] for _ in range(n + 1)] for _ in range(NO_OF_DIMENSIONS)]

for dimension, no_of_edges in enumerate(no_of_edges_by_dim):
    graph = graph_by_dimension[dimension]
    for _ in range(no_of_edges):
        p, q = (int(x) for x in input().split())
        graph[p].append(q)
        graph[q].append(p)

components_ids_by_vertex = [[None] * NO_OF_DIMENSIONS for _ in range(n + 1)]

def dfs(dimension_id, vertex_id, colour):
    components_ids_by_vertex[vertex_id][dimension_id] = colour
    for s in graph_by_dimension[dimension_id][vertex_id]:
        if not components_ids_by_vertex[s][dimension_id]:
            dfs(dimension_id, s, colour)

for i in range(NO_OF_DIMENSIONS):
    for j in range(1, n + 1):
        if not components_ids_by_vertex[j][i]:
            dfs(i, j, j)

components_ids_by_vertex = [tuple(x) for x in components_ids_by_vertex]

results = collections.Counter(components_ids_by_vertex)

for i in range(1, n + 1):
    print(results[components_ids_by_vertex[i]], end=' ')
print()

Submission status: Runtime Error

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

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

    return list(d.values())

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

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

Submission status: Runtime Error

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

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

    return list(d.values())

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

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

Submission status: Runtime Error

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

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

def dfs_road(t_node, group_num):
    global road_group, road_belong_group, node_seen
    road_belong_group[t_node] = group_num
    road_group[group_num].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, group_num)

def dfs_train(t_node, group_num):
    global node_seen, train_group, train_belong_group
    train_belong_group[t_node] = group_num
    train_group[group_num].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, group_num)

def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group
    # 入力
    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)
        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)
        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: Runtime Error

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

road = {}
train = {}
node_all = set()
node_seen = set()
road_belong_group = []
train_belong_group = []
road_group = {}
train_group = {}

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

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

def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group
    # 入力
    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)
        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)
        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] & train_group[tg] )
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

import sys
input = sys.stdin.readline

road = {}
train = {}
node_all = set()
node_seen = set()
road_belong_group = []
train_belong_group = []
road_group = {}
train_group = {}

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

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

def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group
    # 入力
    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)}
    node_checked_road = 0
    node_checked_train = 0

    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)

    # 処理
    ## 道路
    road_group[-1] = set()
    train_group[-1] = set()

    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)
        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)
        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] & train_group[tg] )
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

road = {}
train = {}
node_all = set()
node_seen = set()
road_belong_group = []
train_belong_group = []
road_group = {}
train_group = {}

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

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

def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group
    # 入力
    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)}
    node_checked_road = 0
    node_checked_train = 0

    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)

    # 処理
    ## 道路
    road_group[-1] = set()
    train_group[-1] = set()

    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)
        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)
        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] & train_group[tg] )
            if linked_city == 0:
                linked_city += 1
            print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

import sys
input = sys.stdin.readline
large_p = 10**9 + 7

road = {}
train = {}
node_all = set()
node_seen = set()
road_belong_group = []
train_belong_group = []
road_group = {}
train_group = {}

def dfs_road(t_node, group_num):
    global node_seen, road_group, road_belong_group
    node_seen.add(t_node)
    road_belong_group[t_node] = group_num
    road_group[group_num].add(t_node)
    next_nodes = set(road[t_node]) - node_seen
    if not list(next_nodes):
        return
    else:
        for next in next_nodes:
            dfs_road(next, group_num)

def dfs_train(t_node, group_num):
    global node_seen, train_group, train_belong_group
    node_seen.add(t_node)
    train_belong_group[t_node] = group_num
    train_group[group_num].add(t_node)
    next_nodes = set(train[t_node]) - node_seen
    if not list(next_nodes):
        return
    else:
        for next in next_nodes:
            dfs_train(next, group_num)

def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group
    # 入力
    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)}
    road_belong_group = [0] * (n + 1)
    train_belong_group = [0] * (n + 1)
    road_belong_group[0] = -1
    train_belong_group[0] = -1

    for _ in range(k):
        p, q = map(int, input().split())
        road[p].append(q)
        road[q].append(p)
    train = {e:[] for e in range(1, n + 1)}
    for _ in range(l):
        s, t = map(int, input().split())
        train[s].append(t)
        train[t].append(s)

    # 処理
    ## 道路
    road_group[-1] = set()
    train_group[-1] = set()

    group_num_road = 1
    while list(node_all - node_seen):
        node_remain = road_belong_group.index(0)
        if node_remain == 0:
            node_remain = 1
        if not road[node_remain]:
            road_belong_group[node_remain] = -1
            node_seen.add(node_remain)
            continue
        road_group[group_num_road] = set()
        dfs_road(node_remain, group_num_road)
        group_num_road += 1


    ## 鉄道
    group_num_train = 1
    node_seen = set()
    while list(node_all - node_seen):
        node_remain = train_belong_group.index(0)
        if node_remain == 0:
            node_remain = 1
        if not train[node_remain]:
            train_belong_group[node_remain] = -1
            node_seen.add(node_remain)
            continue
        train_group[group_num_train] = set()
        dfs_train(node_remain, group_num_train)
        group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        linked_city = len(road_group[road_belong_group[i]] & train_group[train_belong_group[i]] )
        if linked_city == 0:
            linked_city += 1
        print(linked_city, end = ' ')


if __name__ == '__main__':
    main()