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
sys.setrecursionlimit(4100000)

import math

import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

from functools import reduce

from itertools import combinations


class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [1 for _ in range(n)]

    def findRoot(self, i):
        if self.parent[i] == i:  # 親が自分ならroot
            return i
        else:
            self.parent[i] = self.findRoot(self.parent[i])  # 親をrootに付け替える
            return self.parent[i]

    def unite(self, i, j):
        i_root = self.findRoot(i)
        j_root = self.findRoot(j)
        if i_root == j_root:
            return

        if self.rank[i_root] > self.rank[j_root]:  # ランクが高い方を親にする。
            self.parent[j_root] = i_root
        elif self.rank[i_root] == self.rank[j_root]:
            self.parent[j_root] = i_root
            self.rank[i_root] += 1
        else:
            self.parent[i_root] = j_root

        return i

    def isSame(self, i, j):
        return self.findRoot(i) == self.findRoot(j)

    def setGroup(self, elements):
        reduce(self.unite, elements)


class UnionFindCounter:
    def __init__(self, n):
        self.N = n
        self.parent = list(range(n))
        self.rank = [1 for _ in range(n)]
        self._count = [1 for _ in range(n)]

    def findRoot(self, i):
        if self.parent[i] == i:  # 親が自分ならroot
            return i
        else:
            self.parent[i] = self.findRoot(self.parent[i])  # 親をrootに付け替える
            return self.parent[i]

    def unite(self, i, j):
        i_root = self.findRoot(i)
        j_root = self.findRoot(j)
        if i_root == j_root:
            return

        if self.rank[i_root] > self.rank[j_root]:  # ランクが高い方を親にする。
            self.parent[j_root] = i_root
            self._count[i_root] += self._count[j_root]
        elif self.rank[i_root] == self.rank[j_root]:
            self.parent[j_root] = i_root
            self.rank[i_root] += 1
            self._count[i_root] += self._count[j_root]
        else:
            self.parent[i_root] = j_root
            self._count[j_root] += self._count[i_root]

        return i

    def isSame(self, i, j):
        return self.findRoot(i) == self.findRoot(j)

    def setGroup(self, elements):
        reduce(self.unite, elements)

    def getCount(self):
        return [self._count[self.findRoot(i)] for i in range(self.N)]


def resolve():
    # S = [x for x in sys.stdin.readline().split()][0]  # 文字列 一つ
    # N = [int(x) for x in sys.stdin.readline().split()][0]  # int 一つ
    N, K, L = [int(x) for x in sys.stdin.readline().split()]  # 複数int
    # grid = [list(sys.stdin.readline().split()[0]) for _ in range(N)]  # 文字列grid
    grid = [
        tuple([int(x) - 1 for x in sys.stdin.readline().split()])
        for _ in range(K + L)
    ]  # int grid

    logger.debug('{}'.format([]))

    p_uf = UnionFind(N)
    r_uf = UnionFind(N)
    both_uf = UnionFindCounter(N)

    for k in range(K):
        p, q = grid[k]
        p_uf.unite(p, q)

    for l in range(K, K + L):
        r, s = grid[l]
        r_uf.unite(r, s)

    for (p, q) in combinations(range(N), 2):
        if p_uf.isSame(p, q) and r_uf.isSame(p, q):
            both_uf.unite(p, q)

    print(' '.join([str(x) for x in both_uf.getCount()]))


if __name__ == "__main__":
    resolve()

# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる

import sys
from io import StringIO
import unittest


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """4 3 1
1 2
2 3
3 4
2 3"""
        output = """1 2 2 1"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """4 2 2
1 2
2 3
1 4
2 3"""
        output = """1 2 2 1"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """7 4 4
1 2
2 3
2 5
6 7
3 5
4 5
3 4
6 7"""
        output = """1 1 2 1 2 2 2"""
        self.assertIO(input, output)

    def test_入力例_4(self):
        input = """2 1 1
1 2
1 2"""
        output = """2 2"""
        self.assertIO(input, output)

    def test_入力例_5(self):
        input = """4 3 3
1 2
1 4
1 3
1 4
4 3
2 3"""
        output = """4 4 4 4"""
        self.assertIO(input, output)

    def test_入力例_6(self):
        input = """5 3 4
1 2
2 3
3 4
1 5
5 4
4 3
3 2"""
        output = """4 4 4 4 1"""
        self.assertIO(input, output)

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 members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

n,k,l=map(int,input().split())
uf1=UnionFind(n)
for _ in range(k):
    p,q=map(int,input().split())
    uf1.union(p-1,q-1)
uf2=UnionFind(n)
for _ in range(l):
    p,q=map(int,input().split())
    uf2.union(p-1,q-1)
ans=[]
for i in range(n):
    a=set(uf1.members(i))
    b=set(uf2.members(i))
    c=a&b
    print(len(c))

Submission status: Time Limit Exceeded

Solution code:
def deep_search(L,i,f):
    Q=L[i]
    if f[i]==0:
        f[i]=i
        for j in L[i]:
            f[j]=i
        while Q!=[]:
            p=Q.pop()
            Q=Q+L[p]
            for j in L[p]:
                f[j]=i
    return f

N,K,L=input().split(" ")
N=int(N)
K=int(K)
L=int(L)
a=[0 for i in range(N+1)]
b=[0 for i in range(N+1)]
road=[[] for i in range(N+1)]
train=[[] for i in range(N+1)]
for i in range(K+L):
    p,q=input().split(" ")
    p=int(p)
    q=int(q)
    if i<K:
        road[p].append(q)
    else:
        train[p].append(q)
for i in range(1,N+1):
    a=deep_search(road,i,a)
    b=deep_search(train,i,b)
ans=[[a[i],b[i]] for i in range(1,N+1)]
for i in range(N):
    print(ans.count(ans[i]),end=" ")

Submission status: Time Limit Exceeded

Solution code:
def deep_search(L,i,f):
    Q=L[i]
    if f[i]==0:
        f[i]=i
        for j in L[i]:
            f[j]=i
        while Q!=[]:
            p=Q.pop()
            Q=Q+L[p]
            for j in L[p]:
                f[j]=i
    return f

N,K,L=input().split(" ")
N=int(N)
K=int(K)
L=int(L)
a=[0 for i in range(N+1)]
b=[0 for i in range(N+1)]
road=[[] for i in range(N+1)]
train=[[] for i in range(N+1)]
for i in range(K+L):
    p,q=input().split(" ")
    p=int(p)
    q=int(q)
    if i<K:
        road[p].append(q)
    else:
        train[p].append(q)
for i in range(1,N+1):
    a=deep_search(road,i,a)
    b=deep_search(train,i,b)
ans=[]
for i in range(1,N+1):
    time=0
    for j in range(1,N+1):
        if a[i]==a[j] and b[i]==b[j]:
            time+=1
    print(time,end=" ")

Submission status: Time Limit Exceeded

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

#初期化
train_connection_group_dict = dict() #key:group No, value:connection cities set
road_connection_group_dict = dict() #key:group No, value:connection cities set

for i in range(1,N+1):
    train_connection_group_dict[i] = set([i]) #key:group No, value:connection cities set
    road_connection_group_dict[i] = set([i]) #key:group No, value:connection cities set

city_road_group_list = [i for i in range(0,N+1)]
city_train_group_list = [i for i in range(0,N+1)]

#道路の接続をグループ化
for i in range(K):
    p,q = map(int, input().split())
        
    p_group_number = city_road_group_list[p]
    q_group_number = city_road_group_list[q]
    
    if p_group_number != q_group_number:
        p_group_len = len(road_connection_group_dict[p_group_number])
        q_group_len = len(road_connection_group_dict[q_group_number])
        
        if p_group_len > q_group_len:
            merge_group_number = p_group_number
            merged_group_number = q_group_number
        else:
            merge_group_number = q_group_number
            merged_group_number = p_group_number
            
        #統合される側の所属グループを書き換え
        for city in road_connection_group_dict[merged_group_number]:
            city_road_group_list[city] = merge_group_number

        #統合する
        road_connection_group_dict[merge_group_number] |= road_connection_group_dict[merged_group_number]
        #統合された側を消去
        road_connection_group_dict[merged_group_number] = set()     

        
#鉄道の接続をグループ化
for i in range(L):
    p,q = map(int, input().split())
        
    p_group_number = city_train_group_list[p]
    q_group_number = city_train_group_list[q]
    
    if p_group_number != q_group_number:
        p_group_len = len(train_connection_group_dict[p_group_number])
        q_group_len = len(train_connection_group_dict[q_group_number])
        
        if p_group_len > q_group_len:
            merge_group_number = p_group_number
            merged_group_number = q_group_number
        else:
            merge_group_number = q_group_number
            merged_group_number = p_group_number

        #統合される側の所属グループを書き換え
        for city in train_connection_group_dict[merged_group_number]:
            city_train_group_list[city] = merge_group_number

        #統合する
        train_connection_group_dict[merge_group_number] |= train_connection_group_dict[merged_group_number]
        #統合された側を消去
        train_connection_group_dict[merged_group_number] = set()

#City毎に道路・鉄道で接続しているCityを出し、積集合を取る
ans = []
for i in range(1,N+1):
    #print("City:",i)
    connectin_by_road = road_connection_group_dict[city_road_group_list[i]]
    connectin_by_train = train_connection_group_dict[city_train_group_list[i]]
    #print(" by road",connectin_by_road)
    #print(" by train",connectin_by_train)
    connectin_by_both = connectin_by_road & connectin_by_train
    #print(" by both",connectin_by_both)
    ans.append(len(connectin_by_both))
    
print(' '.join(map(str,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())

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

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

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

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

for i in range(n):
   print(pair.count(pair[i]))

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())

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

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

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

for i in range(n):
   print(len(set(uf1.members(i)) & set(uf2.members(i))))

Submission status: Time Limit Exceeded

Solution code:
class UnionFind():
    def __init__(self, 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


N, K, L = map(int, input().split())
uf = UnionFind(2 * N)
for _ in range(K):
    p, q = map(int, input().split())
    uf.union(p - 1, q - 1)

for _ in range(L):
    r, s = map(int, input().split())
    uf.union(r - 1 + N, s - 1 + N)

ans = [0] * N
for i in range(N):
    cnt = 0
    for j in range(N):
        if uf.find(i) == uf.find(j) and uf.find(i + N) == uf.find(j + N):
            cnt += 1
    ans[i] = cnt

for i in range(N - 1):
    print(ans[i], end=' ')
print(ans[N - 1])

Submission status: Time Limit Exceeded

Solution code:
# union-find木
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本の鉄道
N, K, L = map(int, input().split())

# N都市を初期の要素数とする
# 道路と鉄道をそれぞれ別のunion-find木として表現する
uf_p = UnionFind(N)
uf_t = UnionFind(N)

# 道路の木
for _ in range(K):
    x,y = map(int, input().split())
    uf_p.union(x-1,y-1)

# 鉄道の木
for _ in range(L):
    x,y = map(int, input().split())
    uf_t.union(x-1,y-1)

    
# 出力結果を整形
result = []
for i in range(N):
    # 道路と鉄道の両方繋がっている件数をand条件で抽出する
    # result.append(str(len(set(uf_p.members(i)) & set(uf_t.members(i)))))

    print(str(len(set(uf_p.members(i)) & set(uf_t.members(i)))),end=" ")
#print(" ".join(result))

Submission status: Time Limit Exceeded

Solution code:
# union-find木
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本の鉄道
N, K, L = map(int, input().split())

# N都市を初期の要素数とする
# 道路と鉄道をそれぞれ別のunion-find木として表現する
uf_p = UnionFind(N)
uf_t = UnionFind(N)

# 道路の木
for _ in range(K):
    x,y = map(int, input().split())
    uf_p.union(x-1,y-1)

# 鉄道の木
for _ in range(L):
    x,y = map(int, input().split())
    uf_t.union(x-1,y-1)

    
# 出力結果を整形
result = []
for i in range(N):
    # 道路と鉄道の両方繋がっている件数をand条件で抽出する
    result.append(str(len(set(uf_p.members(i)) & set(uf_t.members(i)))))

print(" ".join(result))

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]
 
## 
# N個の都市
# K本の道路
# L本の鉄道
N, K, L = map(int, input().split())

# N都市を初期の要素数とする
# 道路と鉄道をそれぞれ別のunion-find木として表現する
uf_p = UnionFind(N)
uf_t = UnionFind(N)

# 道路の木
for _ in range(K):
    x,y = map(int, input().split())
    uf_p.union(x-1,y-1)

# 鉄道の木
for _ in range(L):
    x,y = map(int, input().split())
    uf_t.union(x-1,y-1)

    
# 出力結果を整形
result = []
for i in range(N):
    # 道路と鉄道の両方繋がっている件数をand条件で抽出する
    result.append(str(len(set(uf_p.members(i)) & set(uf_t.members(i)))))
    
print(" ".join(result))

Submission status: Time Limit Exceeded

Solution code:
# union-find木
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本の鉄道
N, K, L = map(int, input().split())

# N都市を初期の要素数とする
# 道路と鉄道をそれぞれ別のunion-find木として表現する
uf_p = UnionFind(N)
uf_t = UnionFind(N)

# 道路の木
for _ in range(K):
    x,y = map(int, input().split())
    uf_p.union(x-1,y-1)

# 鉄道の木
for _ in range(L):
    x,y = map(int, input().split())
    uf_t.union(x-1,y-1)

# 道路と鉄道の両方繋がっている件数をand条件で抽出する
result = [(str(len(set(uf_p.members(i)) & set(uf_t.members(i))))) for i in range(N)]
    
print(" ".join(result))

Submission status: Time Limit Exceeded

Solution code:
# union-find木
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本の鉄道
N, K, L = map(int, input().split())

# 道路の一覧
p = [list(map(int, input().split())) for _ in range(K)]

# 鉄道の一覧
r = [list(map(int, input().split())) for _ in range(L)]

# N都市を初期の要素数とする
# 道路と鉄道をそれぞれ別のunion-find木として表現する
uf_p = UnionFind(N)
uf_t = UnionFind(N)

# 道路の木
for px,py in p:
    uf_p.union(px-1,py-1)

# 鉄道の木
for rx,ry in r:
    uf_t.union(rx-1,ry-1)

    
# 出力結果を整形
result = []
for i in range(N):
    # 道路と鉄道の両方繋がっている件数をand条件で抽出する
    result.append(str(len(set(uf_p.members(i)) & set(uf_t.members(i)))))

print(" ".join(result))

Submission status: Time Limit Exceeded

Solution code:
# 参考URL
# https://note.nkmk.me/python-union-find/
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.rank = [0] * 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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.parents[x] = y
        else:
            self.parents[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

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

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


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

uf_road = UnionFind(N)
uf_train = UnionFind(N)

for _ in range(K):
    a, b = map(int, input().split())
    uf_road.union(a-1, b-1)
    
for _ in range(L):
    a, b = map(int, input().split())
    uf_train.union(a-1, b-1)

ans = []
for i in range(N):
    links = set(uf_road.members(i)) & set(uf_train.members(i))
    ans.append(len(links))
    
print(' '.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
# 参考URL
# https://note.nkmk.me/python-union-find/
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 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]


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

uf_road = UnionFind(N)
uf_train = UnionFind(N)

for _ in range(K):
    a, b = map(int, input().split())
    uf_road.union(a-1, b-1)
    
for _ in range(L):
    a, b = map(int, input().split())
    uf_train.union(a-1, b-1)

ans = []
for i in range(N):
    links = set(uf_road.members(i)) & set(uf_train.members(i))
    ans.append(len(links))
    
print(' '.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
import sys

if sys.platform =='ios':
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

class UnionFind():
	def __init__(self, n):
		self.n = n
		self.parents = [-1] * n
	
	def root(self, x):
		if self.parents[x] < 0:
			return x
		else:
			self.parents[x] = self.root(self.parents[x]) # 経路圧縮
			
			return self.parents[x]
	
	def same(self, x, y):
		return self.root(x) == self.root(y)
	
	def unite(self, x, y):
		x = self.root(x)
		y = self.root(y)
		
		if (x == y): return
		
		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.root(x)]

N, K, L = MAP()

road = UnionFind(N)
train = UnionFind(N)

for _ in range(K):
	x, y = MAP()
	road.unite(x-1, y-1)

for _ in range(L):
	x, y = MAP()
	train.unite(x-1, y-1)

for i in range(N):
	print(sum([1 for j in range(N) if road.same(i, j) and train.same(i, j)]))

Submission status: Time Limit Exceeded

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

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

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

ufRoad = UnionFind()

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

ufRail = UnionFind()

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

SRoad = [set() for i in range(N)]
SRail = [set() for i in range(N)]

for i in range(N):
  ufRoad.root(i)
  ufRail.root(i)

for i in range(N):
  SRoad[ufRoad.par[i]].add(i)
  SRail[ufRail.par[i]].add(i)

r = [0] * N
for i in range(N):
  r[i] = len(SRoad[ufRoad.par[i]] & SRail[ufRail.par[i]])

print(*r)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations
class UnionFind():
  def __init__(self, x):
    self.x=x
    self.root=[-1]*(N+1)
    self.rnk=[0]*(N+1)
  
  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):
    x = self.Find_root(x)
    y = self.Find_root(y)
    if x==y:
      return
    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
      if self.rnk[x]==self.rnk[y]:
        self.rnk[y]+=1
  
  def isSameGroup(self, x, y):
    return self.Find_root(x)==self.Find_root(y)
  
  def Count(self, x):
    return -self.root[self.Find_root(x)]
N,K,L=map(int,input().split())
u1=UnionFind(N)
u2=UnionFind(N)
for _ in range(K):
  x,y=map(int,input().split())
  u1.Unite(x,y)
for _ in range(L):
  x,y=map(int,input().split())
  u2.Unite(x,y)

l=[1]*N
for i,j in combinations(range(N),2):
  if u1.isSameGroup(i+1,j+1) and u2.isSameGroup(i+1,j+1):
    l[i]+=1
    l[j]+=1
  else:
    continue
l=[str(n) for n in l]
print(' '.join(l))