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.ps = [-1]*(n+1)
    def find(self,x):
        if self.ps[x]<0:
            return x
        else:
            self.ps[x]=self.find(self.ps[x])
            return self.ps[x]
    def unite(self,x,y):
        x=self.find(x)
        y=self.find(y)
        if x==y:
            return False
        if self.ps[x]>self.ps[y]:
            x,y = y,x
        self.ps[x] += self.ps[y]
        self.ps[y] = x
        return True
    def same(self,x,y):
        return self.find(x)==self.find(y)
    def size(self,x):
        x = self.find(x)
        return -self.ps[x]
      
n,k,l = map(int,input().split())
tg = UnionFind(n)
rg = UnionFind(n)
for _ in range(k):
  p,q = map(int, input().split())
  rg.unite(p,q)
for _ in range(l):
  p,q = map(int, input().split())
  tg.unite(p,q)
ans = [1]*(n+1)
for i in range(1,n):
  for j in range(i+1,n+1):
    if rg.same(i,j) and tg.same(i,j):
      ans[i] += 1
      ans[j] += 1
print(" ".join(map(str,ans[1:])))

Submission status: Time Limit Exceeded

Solution code:
def c_show(graph,x):
    seen = set()
    nodes = set([x])
    while nodes:
        cur = nodes.pop()
        seen.add(cur)
        nodes |= set(graph[cur]) - seen
    return seen

def c_cnt(graph,n):
    gnum = 1
    grp = [0]*n
    for x in range(n):
        if not grp[x]:
            for i in c_show(graph,x):
                grp[i] = gnum
            gnum += 1
    return grp
  
n,k,l = map(int,input().split())
tg = [list() for _ in range(n)]
rg = [list() for _ in range(n)]
for _ in range(k):
  p,q = map(int, input().split())
  rg[p-1].append(q-1)
  rg[q-1].append(p-1)
for _ in range(l):
  p,q = map(int, input().split())
  tg[p-1].append(q-1)
  tg[q-1].append(p-1)
done = [0]*n
rl = []
for i in range(n):
  if not done[i]:
    curs = c_show(rg,i)
    for x in curs:
      done[x] = 1
    rl.append(curs)
tl = c_cnt(tg,n)
ans = [0]*n
for x in rl:
  for i in x:
    for j in x:
      if tl[i] == tl[j]:
        ans[i] += 1
        ans[j] += 1
for x in range(n):
  ans[x]//=2
print(" ".join(map(str,ans)))

Submission status: Time Limit Exceeded

Solution code:
def c_show(graph,x):
    seen = set()
    nodes = set([x])
    while nodes:
        cur = nodes.pop()
        seen.add(cur)
        nodes |= set(graph[cur]) - seen
    return seen

def c_cnt(graph,n):
    gnum = 1
    grp = [0]*n
    for x in range(n):
        if not grp[x]:
            for i in c_show(graph,x):
                grp[i] = gnum
            gnum += 1
    return grp
  
n,k,l = map(int,input().split())
tg = [list() for _ in range(n)]
rg = [list() for _ in range(n)]
for _ in range(k):
  p,q = map(int, input().split())
  rg[p-1].append(q-1)
  rg[q-1].append(p-1)
for _ in range(l):
  p,q = map(int, input().split())
  tg[p-1].append(q-1)
  tg[q-1].append(p-1)
done = [0]*n
rl = []
for i in range(n):
  if not done[i]:
    curs = c_show(rg,i)
    for x in curs:
      done[x] = 1
    rl.append(curs)
tl = c_cnt(tg,n)
ans = [0]*n
for x in rl:
  for i in x:
    for j in x:
      if tl[i] == tl[j]:
        ans[i] += 1
        ans[j] += 1
for x in range(n):
  ans[x]//=2
print(" ".join(map(str,ans)))

Submission status: Time Limit Exceeded

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

class UnionFind:
    def __init__(self, n):
        self.n = n
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    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 unite(self, u, v):
        ru = self.root(u)
        rv = self.root(v)
        if self.rank[ru] < self.rank[rv]:
            self.par[ru] = rv
        else:
            self.par[rv] = ru
            if self.rank[ru] == self.rank[rv]:
                self.rank[ru] += 1

    def same(self, u, v):
        return self.root(u) == self.root(v)


u_road = UnionFind(N)
u_train = UnionFind(N)

for i in range(K):
    p, q = map(int, input().split())
    u_road.unite(p, q)
for i in range(L):
    r, s = map(int, input().split())
    u_train.unite(r, s)

ans = [1] * N

for i in range(1, N):
    for j in range(i+1, N+1):
        if u_road.same(i, j) and u_train.same(i, j):
            ans[i-1] += 1
            ans[j-1] += 1

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

class UnionFind(object):
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0 for i in range(n + 1)]

    def find(self, x):
        if self.par[x] == x:
            return x
        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 self.rank[x] < self.rank[y]:
            self.par[x] = y
        elif self.rank[x] > self.rank[y]:
            self.par[y] = x
        else:
            self.par[y] = x
            self.rank[x] += 1

sys.setrecursionlimit(10 ** 5 + 1)

n, k, l = map(int, input().split())
Ur = UnionFind(n)
for i in range(k):
    p, q = map(int, input().split())
    Ur.union(p, q)

Ut = UnionFind(n)
for i in range(l):
    r, s = map(int, input().split())
    Ut.union(r, s)

x = [[Ur.find(i + 1), Ut.find(i + 1)] for i in range(n)]
ans = []
for i in range(n):
    ans.append(x.count(x[i]))
print(' '.join([str(a) for a in ans]))

Submission status: Time Limit Exceeded

Solution code:
import sys, time
from collections import defaultdict

sys.setrecursionlimit(10 ** 5 + 1)

def dfs(i, V, E, num):
    V[i] = num
    for j in [x for x in E[i] if V[x] == 0]:
        if V[j] > 0:
            continue
        V = dfs(j, V, E, num)
    return V

n, k, l = map(int, input().split())
Er = defaultdict(list)
for i in range(k):
    p, q = map(int, input().split())
    Er[p].append(q)
    Er[q].append(p)
Et = defaultdict(list)
for i in range(l):
    r, s = map(int, input().split())
    Et[r].append(s)
    Et[s].append(r)

#start = time.time()
Vr_group = [None]
Vr = [0 for _ in range(n + 1)]
j = 1
for i in range(1, n + 1):
    if Vr[i] > 0:
        continue
    Vr = dfs(i, Vr, Er, j)
    Vr_group.append({t for t in range(1, n + 1) if Vr[t] == j})
    j += 1
#print(time.time() - start)

#start = time.time()
Vt_group = [None]
Vt = [0 for _ in range(n + 1)]
j = 1
for i in range(1, n + 1):
    if Vt[i] > 0:
        continue
    Vt = dfs(i, Vt, Et, j)
    Vt_group.append({t for t in range(1, n + 1) if Vt[t] == j})
    j += 1
#print(time.time() - start)

#start = time.time()
W = [[0 for j in range(len(Vt_group))] for i in range(len(Vr_group))]
for i in range(1, len(Vr_group)):
    for j in range(1, len(Vt_group)):
        W[i][j] = len(Vr_group[i] & Vt_group[j])
ans = []
for i in range(1, n + 1):
    ans.append(W[Vr[i]][Vt[i]])
#print(time.time() - start)
print(' '.join([str(x) for x in ans]))

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 5 + 1)

def dfs(i, V, E, num):
    V[i] = num
    for j in E[i]:
        if V[j] > 0:
            continue
        V = dfs(j, V, E, num)
    return V

n, k, l = map(int, input().split())
Er = defaultdict(list)
for i in range(k):
    p, q = map(int, input().split())
    Er[p].append(q)
    Er[q].append(p)
Et = defaultdict(list)
for i in range(l):
    r, s = map(int, input().split())
    Et[r].append(s)
    Et[s].append(r)

Vr_group = [None]
Vr = [0 for _ in range(n + 1)]
j = 1
for i in range(1, n + 1):
    if Vr[i] > 0:
        continue
    Vr = dfs(i, Vr, Er, j)
    Vr_group.append({t for t in range(1, n + 1) if Vr[t] == j})
    j += 1

Vt_group = [None]
Vt = [0 for _ in range(n + 1)]
j = 1
for i in range(1, n + 1):
    if Vt[i] > 0:
        continue
    Vt = dfs(i, Vt, Et, j)
    Vt_group.append({t for t in range(1, n + 1) if Vt[t] == j})
    j += 1

W = [[0 for j in range(len(Vt_group))] for i in range(len(Vr_group))]
for i in range(1, len(Vr_group)):
    for j in range(1, len(Vt_group)):
        W[i][j] = len(Vr_group[i] & Vt_group[j])
ans = []
for i in range(1, n + 1):
    ans.append(W[Vr[i]][Vt[i]])
print(' '.join([str(x) for x in ans]))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, defaultdict

def read_input():
    n, k, l = map(int, input().split())
    roads = []
    for i in range(k):
        p, q = map(int, input().split())
        roads.append((p, q))

    rails = []
    for j in range(l):
        r, s = map(int, input().split())
        rails.append((r, s))

    return n, k, l, roads, rails

# nodes = [1, 2, ...]
# edges = [(x, y), (x, y), ...]
def graph_connected_component(nodes, nd_edges):

    # 無向グラフを想定、edgesを両向きにはやす
    edge_table = {n:[] for n in nodes}
    for e in nd_edges:
        edge_table[e[0]].append(e[1])
        edge_table[e[1]].append(e[0])

    reach_nodes = set()
    result = []
    while reach_nodes != set(nodes):
        node_q = deque()
        component = set()

        # まだ見ていないnodeを基点にしてcomponentを構成
        for node in nodes:
            if node not in reach_nodes:
                node_q.appendleft(node)
                break

        # qがある = 連結先があるので探索
        while len(node_q) > 0:
            curr = node_q.pop()
            reach_nodes.add(curr)
            component.add(curr)

            # 連結先のうち、まだ未探索nodeをqにつむ
            next_nodes = edge_table[curr]
            for node in next_nodes:
                if node not in component:
                    node_q.appendleft(node)

        result.append(component)
    return result


def submit():
    n, k, l, roads, rails = read_input()
    nodes = list(range(1, n + 1))
    road_components = graph_connected_component(nodes, roads)
    rail_components = graph_connected_component(nodes, rails)

    road_ids = [-1] * (n + 1)
    rail_ids = [-1] * (n + 1)

    for i, c in enumerate(road_components):
        for node in c:
            road_ids[node] = i + 1

    for i, c in enumerate(rail_components):
        for node in c:
            rail_ids[node] = i + 1

    count = defaultdict(int)
    for node in nodes:
        count[(road_ids[node], rail_ids[node])] += 1

    print(' '.join([str(count[(road_ids[node], rail_ids[node])]) for node in nodes]))


if __name__ == '__main__':
    submit()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def read_input():
    n, k, l = map(int, input().split())
    roads = []
    for i in range(k):
        p, q = map(int, input().split())
        roads.append((p, q))

    rails = []
    for j in range(l):
        r, s = map(int, input().split())
        rails.append((r, s))

    return n, k, l, roads, rails

# nodes = [1, 2, ...]
# edges = [(x, y), (x, y), ...]
def graph_connected_component(nodes, nd_edges):

    # 無向グラフを想定、edgesを両向きにはやす
    edge_table = {n:[] for n in nodes}
    for e in nd_edges:
        edge_table[e[0]].append(e[1])
        edge_table[e[1]].append(e[0])

    reach_nodes = set()
    result = []
    while reach_nodes != set(nodes):
        node_q = deque()
        component = set()

        # まだ見ていないnodeを基点にしてcomponentを構成
        for node in nodes:
            if node not in reach_nodes:
                node_q.appendleft(node)
                break

        # qがある = 連結先があるので探索
        while len(node_q) > 0:
            curr = node_q.pop()
            reach_nodes.add(curr)
            component.add(curr)

            # 連結先のうち、まだ未探索nodeをqにつむ
            next_nodes = edge_table[curr]
            for node in next_nodes:
                if node not in component:
                    node_q.appendleft(node)

        result.append(component)
    return result


def submit():
    n, k, l, roads, rails = read_input()
    nodes = list(range(1, n + 1))
    road_components = graph_connected_component(nodes, roads)
    rail_components = graph_connected_component(nodes, rails)

    road_comp_table = {}
    rail_comp_table = {}
    for road_comp in road_components:
        for node in road_comp:
            road_comp_table[node] = road_comp

    for rail_comp in rail_components:
        for node in rail_comp:
            road_comp_table[node] = road_comp_table[node].intersection(rail_comp)

    print(' '.join([str(len(road_comp_table[i])) for i in nodes]))



if __name__ == '__main__':
    submit()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def read_input():
    n, k, l = map(int, input().split())
    roads = []
    for i in range(k):
        p, q = map(int, input().split())
        roads.append((p, q))

    rails = []
    for j in range(l):
        r, s = map(int, input().split())
        rails.append((r, s))

    return n, k, l, roads, rails

# nodes = [1, 2, ...]
# edges = [(x, y), (x, y), ...]
def graph_connected_component(nodes, nd_edges):

    # 無向グラフを想定、edgesを両向きにはやす
    edge_table = {n:[] for n in nodes}
    for e in nd_edges:
        edge_table[e[0]].append(e[1])
        edge_table[e[1]].append(e[0])

    reach_nodes = set()
    result = []
    while reach_nodes != set(nodes):
        node_q = deque()
        component = set()

        # まだ見ていないnodeを基点にしてcomponentを構成
        for node in nodes:
            if node not in reach_nodes:
                node_q.appendleft(node)
                break

        # qがある = 連結先があるので探索
        while len(node_q) > 0:
            curr = node_q.pop()
            reach_nodes.add(curr)
            component.add(curr)

            # 連結先のうち、まだ未探索nodeをqにつむ
            next_nodes = edge_table[curr]
            for node in next_nodes:
                if node not in component:
                    node_q.appendleft(node)

        result.append(component)
    return result


def submit():
    n, k, l, roads, rails = read_input()
    nodes = list(range(1, n + 1))
    road_components = graph_connected_component(nodes, roads)
    rail_components = graph_connected_component(nodes, rails)

    road_comp_table = {}
    rail_comp_table = {}
    for road_comp in road_components:
        for node in road_comp:
            road_comp_table[node] = road_comp

    for rail_comp in rail_components:
        for node in rail_comp:
            rail_comp_table[node] = rail_comp

    count = [len(road_comp_table[n].intersection(rail_comp_table[n])) for n in nodes]
    print(' '.join(map(str, count)))


if __name__ == '__main__':
    submit()

Submission status: Time Limit Exceeded

Solution code:
# UnionFind
class UnionFind(object):
    # 親を表す配列 木はこの配列で表現する
    par = []
    rank = []

    def __init__(self, arg):
        super(UnionFind, self).__init__()
        self.par = [i for i in range(arg)]
        self.rank = [0 for i in range(arg)]

    # 木の根を求める
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # xとyの属する集合を結合
    def unite(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)

        if root_x == root_y:
            return

        if self.rank[root_x] > self.rank[root_y]:
            self.par[root_y] = root_x
        else:
            self.par[root_x] = root_y
            # それぞれの高さが一致する場合のみrankを更新する
            if self.rank[root_x] == self.rank[root_y]:
                self.rank[root_y] += 1

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


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

road_ways = []
rail_ways = []

for _ in range(K):
    road_ways.append(list(map(lambda x: int(x) - 1, input().split())))
for _ in range(L):
    rail_ways.append(list(map(lambda x: int(x) - 1, input().split())))

# 道路、鉄道を記録するUnionFind宣言
road_unionfind = UnionFind(N)
rail_unionfind = UnionFind(N)

# UnionFindを鉄道、道路それぞれで作成
for k in range(K):
    road_unionfind.unite(road_ways[k][0], road_ways[k][1])
for l in range(L):
    rail_unionfind.unite(rail_ways[l][0], rail_ways[l][1])

ans = [0 for _ in range(N)]
for n in range(N):
    # 自分自身は必ず一致しているので１スタート
    sum = 0
    for k in range(N):
        # 鉄道、道路のどちらでも繋がっているならインクリメント
        if road_unionfind.same(n, k) and rail_unionfind.same(n, k):
            sum += 1
    ans[n] = sum

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
N,K,L = map(int, input().split())
pq_list = []
for _ in range(K):
    pq_list.append(list(map(int, input().split())))

rs_list = []
for _ in range(L):
    rs_list.append(list(map(int, input().split())))

class UnionFind():
    def __init__(self):
        self.roots = {}
        self.ranks = {}

    def connect(self,x,y):
        root_x = self.pick_root(x)
        root_y = self.pick_root(y)
        if not root_x == root_y:
            if self.ranks[root_x] >= self.ranks[root_y]:
                # 短い方の根を長い方の根にする
                # 等しいときはxにくっつける
                self.roots[y] = root_x
            else:
                self.roots[x] = root_y

        if self.ranks[root_x]==self.ranks[root_y]:
            # 等しいときxにくっつけると、xのランクが1増える
            self.ranks[x] += 1

    def pick_root(self,k):
        if not k in self.roots:
            self.roots[k] = k
            self.ranks[k] = 1
            return k

        k_root = self.roots[k]
        if k_root == k:
            return k
        else:
            # roots[k] = pick_root(roots[k])を書き足す必要は無いか？(経路圧縮？)
            self.roots[k] = self.pick_root(self.roots[k])
            return self.roots[k]
#             return self.pick_root(self.roots[k])

UF_pq = UnionFind()

for p,q in pq_list:
    UF_pq.connect(p, q)

UF_rs = UnionFind()
for r,s in rs_list:
    UF_rs.connect(r, s)

root_tuples = []
for i in range(1,N+1):
    if not i in UF_pq.roots:
        root_tuples.append((None,None))
        continue
    if not i in UF_rs.roots:
        root_tuples.append((None,None))
        continue
    pq_root = UF_pq.roots[i]
    rs_root = UF_rs.roots[i]
    root_tuples.append((pq_root,rs_root))

from collections import Counter
counter = Counter(root_tuples)
counter[(None,None)] = 1

text = ""
for i in range(N):
    text += str(counter[root_tuples[i]]) + " "

print(text[:-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

N, K, L = [int(a) for a in input().split(" ")]
P, Q = zip(*[[int(v) for v in input().split(" ")] for i in range(K)])
R, S = zip(*[[int(v) for v in input().split(" ")] for i in range(L)])

def find(tab, a):
    if tab[a] == -1: return a
    tab[a] = find(tab, tab[a])
    return tab[a]

def union(tab, a, b):
    pa, pb = (find(tab, a), find(tab, b))
    if pa!=pb:
        tab[pb] = pa

loads = [-1]*N
rails = [-1]*N
for p, q in zip(P, Q):
    union(loads, p-1, q-1)

for r, s in zip(R, S):
    union(rails, r-1, s-1)

ans = []
for i in range(N):
    ans.append(0)
    for j in range(N):
        if find(loads, i)==find(loads, j) and find(rails, i)==find(rails,j):
            ans[-1]+=1

print(" ".join([str(n) for n in ans]))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

N, K, L = [int(a) for a in input().split(" ")]
P, Q = zip(*[[int(v) for v in input().split(" ")] for i in range(K)])
R, S = zip(*[[int(v) for v in input().split(" ")] for i in range(L)])

def find(tab, a):
    if tab[a] == -1: return a
    tab[a] = find(tab, tab[a])
    return tab[a]

def union(tab, a, b):
    pa, pb = (find(tab, a), find(tab, b))
    if pa!=pb:
        tab[pb] = pa

loads = [-1]*N
rails = [-1]*N
for p, q in zip(P, Q):
    union(loads, p-1, q-1)

for r, s in zip(R, S):
    union(rails, r-1, s-1)

dl = defaultdict(set)
dr = defaultdict(set)
for i in range(N):
    dl[find(loads, i)].add(i)
    dr[find(rails, i)].add(i)

ans = [len(dl[find(loads, i)].intersection(dr[find(rails, i)])) for i in range(N)]

print(" ".join([str(n) for n in ans]))

Submission status: Time Limit Exceeded

Solution code:
def main():
	N, K, L = map(int, input().split())
	road = [0]*K
	rail = [0]*L
	road_graph = [[i, 1] for i in range(N+1)]
	rail_graph = [[i, 1] for i in range(N+1)]

	def root(graph, i):
		parent = graph[i][0]
		if parent == i:
			return i
		return root(graph, parent)

	def is_same_tree(graph, i, j):
		return root(graph, i) == root(graph, j)

	def unite(graph, i, j):
		if is_same_tree(graph, i, j):
			return
		l = graph[root(graph, i)]
		r = graph[root(graph, j)]
		if l[1] < r[1]:
			l[0] = r[0]
			r[1] += l[1]
		else:
			r[0] = l[0]
			l[1] += r[0]

	ans_list = [""]*N

	for i in range(K):
		road[i] = list(map(int, input().split()))
		unite(road_graph, road[i][0], road[i][1])
	for i in range(L):
		rail[i] = list(map(int, input().split()))
		unite(rail_graph, rail[i][0], rail[i][1])

	for i in range(1, N+1):
		both_connected = 1
		for j in range(1, N+1):
			if i == j:
				continue
			if is_same_tree(road_graph, i, j) and is_same_tree(rail_graph, i, j):
				both_connected += 1
		this_ans = str(both_connected)
		ans_list[i-1] = this_ans

	ans = " ".join(ans_list)
	print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
def main():
	N, K, L = map(int, input().split())
	road = [0]*K
	rail = [0]*L
	road_graph = [[] for _ in range(N+1)]
	rail_graph = [[] for _ in range(N+1)]
	ans_list = [""]*N
	for i in range(K):
		road[i] = list(map(int, input().split()))
		road_graph[road[i][0]].append(road[i][1])
		road_graph[road[i][1]].append(road[i][0])
	for i in range(L):
		rail[i] = list(map(int, input().split()))
		rail_graph[rail[i][0]].append(rail[i][1])
		rail_graph[rail[i][1]].append(rail[i][0])

	def dfs(start, graph):
		this_ans = set()
		stack = []
		stack.extend(graph[start])
		this_ans.add(start)
		while stack:
			cur = stack.pop()
			if cur in this_ans:
				continue
			this_ans.add(cur)
			stack.extend(graph[cur])
		return this_ans

	road_appeared = defaultdict(set)
	rail_appeared = defaultdict(set)
	for i in range(1, N+1):
		if i not in road_appeared:
			this_roads = dfs(i, road_graph)
			for this_road in this_roads:
				road_appeared[this_road] = this_roads

		if i not in rail_appeared:
			this_rails = dfs(i, rail_graph)
			for this_rail in this_rails:
				rail_appeared[this_rail] = this_rails

		both_connected = road_appeared[i] & rail_appeared[i]
		this_ans = str(len(both_connected))
		ans_list[i-1] = this_ans

	ans = " ".join(ans_list)
	print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
def main():
	N, K, L = map(int, input().split())
	road = [0]*K
	rail = [0]*L
	road_graph = [[] for _ in range(N+1)]
	rail_graph = [[] for _ in range(N+1)]
	ans_list = [""]*N
	for i in range(K):
		road[i] = list(map(int, input().split()))
		road_graph[road[i][0]].append(road[i][1])
		road_graph[road[i][1]].append(road[i][0])
	for i in range(L):
		rail[i] = list(map(int, input().split()))
		rail_graph[rail[i][0]].append(rail[i][1])
		rail_graph[rail[i][1]].append(rail[i][0])

	def dfs(start, graph):
		this_ans = set()
		stack = []
		stack.extend(graph[start])
		this_ans.add(start)
		while stack:
			cur = stack.pop()
			if cur in this_ans:
				continue
			this_ans.add(cur)
			stack.extend(graph[cur])
		return this_ans

	appeared = set()
	for i in range(1, N+1):
		if i in appeared:
			continue
		both_connected = dfs(i, road_graph) & dfs(i, rail_graph)
		this_ans = str(len(both_connected))
		for city in both_connected:
			ans_list[city-1] = this_ans
			appeared.add(city)

	ans = " ".join(ans_list)
	print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
class Unionfind:
    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 check(self, x, y):
        return self.find(x) == self.find(y)
    
    def union(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())
road  = Unionfind(N)
for i in range(K):
    p, q = map(int, input().split())
    road.union(p, q)
rail = Unionfind(N)
for i in range(L):
    r, s = map(int, input().split())
    rail.union(r, s)

num = [[0] * (N+1) for i in range(N+1)]
for i in range(1, 1+N):
    y = road.par[i]
    x = rail.par[i]
    num[y][x] += 1

ans = []
for i in range(1, 1+N):
    y = road.par[i]
    x = rail.par[i]
    ans.append(num[y][x])

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
class Unionfind:
    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 check(self, x, y):
        return self.find(x) == self.find(y)
    
    def union(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())
road  = Unionfind(N)
for i in range(K):
    p, q = map(int, input().split())
    road.union(p, q)
rail = Unionfind(N)
for i in range(L):
    r, s = map(int, input().split())
    rail.union(r, s)

ANS = []
for i in range(1, N+1):
    ans = 0
    for j in range(1, N+1):
        if road.check(i, j) and rail.check(i, j):
            ans += 1
    ANS.append(ans)

print(*ANS)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict

class UnionFind:
    def __init__(self, n):
        self.root = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        self.child = [set([i]) for i in range(n+1)]

    def find(self, x):
        if self.root[x] == x:
            return x
        else:
            y = self.find(self.root[x])
            self.root[x] = y
            self.child[y] |= self.child[x]
            return self.root[x]

    def unite(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if self.rank[rx] < self.rank[ry]:
            self.root[rx] = ry
            self.child[ry] |= self.child[rx]
        else:
            self.root[ry] = rx
            self.child[rx] |= self.child[ry]
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

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

def main():
    input = sys.stdin.readline
    N, K, L = map(int, input().split())
    road = UnionFind(N)
    rail = UnionFind(N)

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

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

    ans = []
    for i in range(N):
        n = road.find(i)
        m = rail.find(i)

        a = len(road.child[n] & rail.child[m])
        ans.append(a)

    return print(*ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict

class UnionFind:
    def __init__(self, n):
        self.root = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

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

    def unite(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if self.rank[rx] < self.rank[ry]:
            self.root[rx] = ry
        else:
            self.root[ry] = rx
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

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

def main():
    input = sys.stdin.readline
    N, K, L = map(int, input().split())
    road = UnionFind(N)
    rail = UnionFind(N)

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

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

    road_r = defaultdict(list)
    rail_r = defaultdict(list)
    for i in range(N):
        road_r[road.find(i)].append(i)
        rail_r[rail.find(i)].append(i)

    memo = [[-1 for _ in range(N)] for _ in range(N)]
    ans = []
    for i in range(N):
        n = road.find(i)
        m = rail.find(i)

        if memo[n][m] != -1:
            ans.append(memo[n][m])
        else:
            a = len(set(road_r[n]) & set(rail_r[m]))
            memo[n][m] = a
            ans.append(a)

    return print(*ans)


if __name__ == '__main__':
    main()