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
n, k, l = [ int(v) for v in input().split() ]
road_parent = [ i for i in range(n) ]
road_set = [ set([i]) for i in range(n) ]
road_list = sorted( [ [ int(v)-1 for v in input().split() ] for i in range(k) ])
rail_parent = [ i for i in range(n) ]
rail_set = [ set([i]) for i in range(n) ]
rail_list = sorted( [ [ int(v)-1 for v in input().split() ] for i in range(l) ])

for i in road_list:
    p, q = i[0], i[1]
    if road_parent[p] != road_parent[q]:
        union_parent, vanish_parent = min(road_parent[p], road_parent[q]), max(road_parent[p], road_parent[q])
        for j in road_set[vanish_parent]:
            road_parent[j] = union_parent
        road_set[union_parent] = road_set[union_parent] | road_set[vanish_parent]
        


for i in rail_list:
    r, s = i[0], i[1]
    if rail_parent[r] != rail_parent[s]:
        union_parent, vanish_parent = min(rail_parent[r], rail_parent[s]), max(rail_parent[r], rail_parent[s])
        for j in rail_set[vanish_parent]:
            rail_parent[j] = union_parent
        rail_set[union_parent] = rail_set[union_parent] | rail_set[vanish_parent]


connect_city = [ None for i in range(n) ]
for i in range(n):
    if connect_city[i] == None:
        rail_and_road = road_set[road_parent[i]] & rail_set[rail_parent[i]]
        connect = len(rail_and_road)
        for j in rail_and_road:
            connect_city[j] = connect
print(*connect_city)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n, k, l = [ int(v) for v in input().split() ]
road_parent = [ i for i in range(n) ]
road_set = [ set([i]) for i in range(n) ]
rail_parent = [ i for i in range(n) ]
rail_set = [ set([i]) for i in range(n) ]

for i in range(k):
    p, q = [ int(v)-1 for v in input().split() ]
    if road_parent[p] != road_parent[q]:
        union_parent, vanish_parent = min(road_parent[p], road_parent[q]), max(road_parent[p], road_parent[q])
        for j in road_set[vanish_parent]:
            road_parent[j] = union_parent
        road_set[union_parent] = road_set[union_parent] | road_set[vanish_parent]
        


for i in range(l):
    r, s = [ int(v)-1 for v in input().split() ]
    if rail_parent[r] != rail_parent[s]:
        union_parent, vanish_parent = min(rail_parent[r], rail_parent[s]), max(rail_parent[r], rail_parent[s])
        for j in rail_set[vanish_parent]:
            rail_parent[j] = union_parent
        rail_set[union_parent] = rail_set[union_parent] | rail_set[vanish_parent]


connect_city = [ None for i in range(n) ]
for i in range(n):
    if connect_city[i] == None:
        rail_and_road = road_set[road_parent[i]] & rail_set[rail_parent[i]]
        connect = len(rail_and_road)
        for j in rail_and_road:
            connect_city[j] = connect
print(*connect_city)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n, k, l = [ int(v) for v in input().split() ]
road_parent = [ i for i in range(n) ]
road_set = [ set([i]) for i in range(n) ]
rail_parent = [ i for i in range(n) ]
rail_set = [ set([i]) for i in range(n) ]

for i in range(k):
    p, q = [ int(v)-1 for v in input().split() ]
    if road_parent[p] != road_parent[q]:
        union_parent, vanish_parent = min(road_parent[p], road_parent[q]), max(road_parent[p], road_parent[q])
        for j in road_set[vanish_parent]:
            road_parent[j] = union_parent
        road_set[union_parent] = road_set[union_parent] | road_set[vanish_parent]
        road_set[vanish_parent].clear()
        


for i in range(l):
    r, s = [ int(v)-1 for v in input().split() ]
    if rail_parent[r] != rail_parent[s]:
        union_parent, vanish_parent = min(rail_parent[r], rail_parent[s]), max(rail_parent[r], rail_parent[s])
        for j in rail_set[vanish_parent]:
            rail_parent[j] = union_parent
        rail_set[union_parent] = rail_set[union_parent] | rail_set[vanish_parent]
        rail_set[vanish_parent].clear()


connect_city = [ None for i in range(n) ]
for i in range(n):
    if connect_city[i] == None:
        rail_and_road = road_set[road_parent[i]] & rail_set[rail_parent[i]]
        connect = len(rail_and_road)
        for j in rail_and_road:
            connect_city[j] = connect
print(*connect_city)

Submission status: Time Limit Exceeded

Solution code:
import os
import sys
from collections import defaultdict

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18

N, K, L = list(map(int, sys.stdin.readline().split()))
P, Q = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(K)]))
R, S = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(L)]))


class UnionFind:
    def __init__(self, size=None, nodes=None):
        """
        size か nodes どっちか指定。
        nodes は set、size は list を使う。
        set の最悪計算量は O(N) なので size 指定のほうが若干速い
        :param int size:
        :param collections.Iterable nodes:
        """
        assert size is not None or nodes is not None
        if size is not None:
            self._parents = [i for i in range(size)]
            self._ranks = [0 for _ in range(size)]
            self._sizes = [1 for _ in range(size)]
        else:
            self._parents = {k: k for k in nodes}
            self._ranks = {k: 0 for k in nodes}
            self._sizes = {k: 1 for k in nodes}

    def unite(self, x, y):
        """
        x が属する木と y が属する木を併合
        :param x:
        :param y:
        :return:
        """
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return

        # rank が小さい方が下
        if self._ranks[x] > self._ranks[y]:
            # x が root
            self._parents[y] = x
            self._sizes[x] += self._sizes[y]
        else:
            # y が root
            self._parents[x] = y
            self._sizes[y] += self._sizes[x]
            if self._ranks[x] == self._ranks[y]:
                self._ranks[y] += 1

    def find(self, x):
        """
        x が属する木の root
        :param x:
        :return:
        """
        if self._parents[x] == x:
            return x
        self._parents[x] = self.find(self._parents[x])
        return self._parents[x]

    def size(self, x):
        """
        x が属する木のノード数
        :param x:
        :return:
        """
        return self._sizes[self.find(x)]


uf1 = UnionFind(size=N + 1)
for p, q in zip(P, Q):
    uf1.unite(p, q)
uf2 = UnionFind(size=N + 1)
for r, s in zip(R, S):
    uf2.unite(r, s)

set1 = defaultdict(set)
set2 = defaultdict(set)
for i in range(1, N + 1):
    set1[uf1.find(i)].add(i)
    set2[uf2.find(i)].add(i)

ans = []
for i in range(1, N + 1):
    ans.append(len(set1[uf1.find(i)] & set2[uf2.find(i)]))
print(' '.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import heapq
import itertools
import math
import os
import re
import string
import sys
from collections import Counter, deque, defaultdict
from decimal import Decimal
from fractions import gcd
from functools import lru_cache, reduce
from operator import itemgetter

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18

N, K, L = list(map(int, sys.stdin.readline().split()))
P, Q = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(K)]))
R, S = list(zip(*[map(int, sys.stdin.readline().split()) for _ in range(L)]))


class UnionFind:
    def __init__(self, size=None, nodes=None):
        """
        size か nodes どっちか指定。
        nodes は set、size は list を使う。
        set の最悪計算量は O(N) なので size 指定のほうが若干速い
        :param int size:
        :param collections.Iterable nodes:
        """
        assert size is not None or nodes is not None
        if size is not None:
            self._parents = [i for i in range(size)]
            self._ranks = [0 for _ in range(size)]
            self._sizes = [1 for _ in range(size)]
        else:
            self._parents = {k: k for k in nodes}
            self._ranks = {k: 0 for k in nodes}
            self._sizes = {k: 1 for k in nodes}

    def unite(self, x, y):
        """
        x が属する木と y が属する木を併合
        :param x:
        :param y:
        :return:
        """
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return

        # rank が小さい方が下
        if self._ranks[x] > self._ranks[y]:
            # x が root
            self._parents[y] = x
            self._sizes[x] += self._sizes[y]
        else:
            # y が root
            self._parents[x] = y
            self._sizes[y] += self._sizes[x]
            if self._ranks[x] == self._ranks[y]:
                self._ranks[y] += 1

    def find(self, x):
        """
        x が属する木の root
        :param x:
        :return:
        """
        if self._parents[x] == x:
            return x
        self._parents[x] = self.find(self._parents[x])
        return self._parents[x]

    def size(self, x):
        """
        x が属する木のノード数
        :param x:
        :return:
        """
        return self._sizes[self.find(x)]


uf1 = UnionFind(size=N + 1)
for p, q in zip(P, Q):
    uf1.unite(p, q)
uf2 = UnionFind(size=N + 1)
for r, s in zip(R, S):
    uf2.unite(r, s)

set1 = defaultdict(set)
set2 = defaultdict(set)
for i in range(1, N + 1):
    set1[uf1.find(i)].add(i)
    set2[uf2.find(i)].add(i)

ans = []
for i in range(1, N + 1):
    ans.append(len(set1[uf1.find(i)] & set2[uf2.find(i)]))
print(' '.join(map(str, ans)))

Submission status: Time Limit Exceeded

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

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

    def root(self, A):
        if self.parent[A] == A:
            return A
        self.parent[A] = self.root(self.parent[A]) #経路縮約
        return self.parent[A]

    def connect(self, A, B):
        A = self.root(A)
        B = self.root(B)
        self.parent[A] = B
        
uni1 = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    if uni1.root(p-1) != uni1.root(q-1):
        uni1.connect(p-1,q-1)

uni2 = UnionFind(N)
for _ in range(L):
    r, s = map(int, input().split())
    if uni2.root(r-1) != uni2.root(s-1):
        uni2.connect(r-1,s-1)

# print (uni1.parent)
# print (uni2.parent)

ans = dict()
key_list = []
for i in range(N): #各都市を検索
    root1 = uni1.root(i) #都市の親を探す
    root2 = uni2.root(i)
    key = str(root1) + '_' + str(root2) #2つの親を連結したものをkeyとする
    key_list.append(key) #リストにkeyを足しておく(=i番目の都市が属するグループとして前からメモ)
    if key in ans.keys(): #dict andに親の組を記録していく
        ans[key] += 1
    else:
        ans[key] = 1
    
for i in range(N):
    print (ans[key_list[i]], end = ' ') #i番目の都市の親の組はkeyで読み出せる
print ()

Submission status: Time Limit Exceeded

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

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

    def root(self, A):
        if self.parent[A] == A:
            return A
        self.parent[A] = self.root(self.parent[A]) #経路縮約
        return self.parent[A]

    def connect(self, A, B):
        A = self.root(A)
        B = self.root(B)
        self.parent[A] = B
        
uni1 = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    if uni1.root(p-1) != uni1.root(q-1):
        uni1.connect(p-1,q-1)

uni2 = UnionFind(N)
for _ in range(L):
    r, s = map(int, input().split())
    if uni2.root(r-1) != uni2.root(s-1):
        uni2.connect(r-1,s-1)

# print (uni1.parent)
# print (uni2.parent)

ans = dict()
key_list = []
for i in range(N):
    root1 = uni1.root(i)
    root2 = uni2.root(i)
    key = str(root1) + '_' + str(root2)
    key_list += [key]
    if key in ans.keys():
        ans[key] += 1
    else:
        ans[key] = 1
    
for i in range(N):
    print (ans[key_list[i]], end = ' ')
print ()






# for i in range(1, N+1):
#     ans = 0
#     for j in range(1, N+1):
#         # print (uni1.root(i), uni1.root(j), uni2.root(i), uni2.root(j))
#         if uni1.root(i) == uni1.root(j) and uni2.root(i) == uni2.root(j):
#             ans += 1
#     print (ans, end = ' ')
print ()

# print (uni1.parent)
# print (uni2.parent)

Submission status: Time Limit Exceeded

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

class UnionFind(object):
    def __init__(self, N):
        self.parent = [-1] * N

    def root(self, A):
        if self.parent[A-1] < 0:
            return A
        self.parent[A-1] = self.root(self.parent[A-1])
        return self.parent[A-1]

    def size(self, A):
        if self.parent[A-1] < 0:
            return -1 * self.parent[A-1]
        return -1 * self.parent[self.root(A)-1]

    def connect(self, A, B):
        A = self.root(A)
        B = self.root(B)
        if A == B:
            return False
        
        if self.size(A) < self.size(B):
            A, B = B, A
        
        self.parent[A-1] += self.parent[B-1]
        self.parent[B-1] = A
        return True
        
uni1 = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    if uni1.root(p) != uni1.root(q):
        uni1.connect(p,q)

uni2 = UnionFind(N)
for _ in range(L):
    r, s = map(int, input().split())
    if uni2.root(r) != uni2.root(s):
        uni2.connect(r,s)

# print (uni1.parent)
# print (uni2.parent)

for i in range(1, N+1):
    ans = 0
    for j in range(1, N+1):
        # print (uni1.root(i), uni1.root(j), uni2.root(i), uni2.root(j))
        if uni1.root(i) == uni1.root(j) and uni2.root(i) == uni2.root(j):
            ans += 1
    print (ans, end = ' ')
print ()

# print (uni1.parent)
# print (uni2.parent)

Submission status: Time Limit Exceeded

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

class UnionFind(object):
    def __init__(self, N):
        self.parent = [-1] * N

    def root(self, A):
        if self.parent[A-1] < 0:
            return A
        self.parent[A-1] = self.root(self.parent[A-1])
        return self.parent[A-1]

    def size(self, A):
        if self.parent[A-1] < 0:
            return -1 * self.parent[A-1]
        return -1 * self.parent[self.root(A)-1]

    def connect(self, A, B):
        A = self.root(A)
        B = self.root(B)
        if A == B:
            return False
        
        if self.size(A) < self.size(B):
            A, B = B, A
        
        self.parent[A-1] += self.parent[B-1]
        self.parent[B-1] = A
        return True
        
uni1 = UnionFind(N)
for _ in range(K):
    p, q = map(int, input().split())
    if uni1.root(p) != uni1.root(q):
        uni1.connect(p,q)

uni2 = UnionFind(N)
for _ in range(L):
    r, s = map(int, input().split())
    if uni2.root(r) != uni2.root(s):
        uni2.connect(r,s)

# print (uni1.parent)
# print (uni2.parent)
for i in range(1, N+1):
    ans = 0
    for j in range(1, N+1):
        # print (uni1.root(i), uni1.root(j), uni2.root(i), uni2.root(j))
        if uni1.root(i) == uni1.root(j) and uni2.root(i) == uni2.root(j):
            ans += 1
    print (ans, end = ' ')
print ()

# print (uni1.parent)
# print (uni2.parent)

Submission status: Time Limit Exceeded

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N, K, L = MI()
    # UnionFind
    class UnionFind():
        def __init__(self, n):
            self.nodes=[-1] * n  # nodes[x]: 負なら、絶対値が木の要素数

        def get_root(self, x):
            # nodes[x]が負ならxが根
            if self.nodes[x] < 0:
                return x
            # 根に直接つなぎ直しつつ、親を再帰的に探す
            else:
                self.nodes[x]=self.get_root(self.nodes[x])
                return self.nodes[x]

        def unite(self, x, y):
            root_x=self.get_root(x)
            root_y=self.get_root(y)
            # 根が同じなら変わらない
            # if root_x == root_y:
            # pass
            if root_x != root_y:
                # 大きい木の方につないだほうが計算量が減る
                if self.nodes[root_x] < self.nodes[root_y]:
                    big_root=root_x
                    small_root=root_y
                else:
                    small_root=root_x
                    big_root=root_y
                self.nodes[big_root] += self.nodes[small_root]
                self.nodes[small_root]=big_root
    uf1=UnionFind(N)
    uf2 = UnionFind(N)
    for _ in range(K):
        p, q = MI_()
        uf1.unite(p, q)
    
    for _ in range(L):
        r, s = MI_()
        uf2.unite(r, s)
    
    set_1 = [set() for _ in range(N)]
    set_2 = [set() for _ in range(N)]

    for i in range(N):
        set_1[uf1.get_root(i)].add(i)
        set_2[uf2.get_root(i)].add(i)
    for i in range(N):
        par_1 = uf1.get_root(i)
        par_2 = uf2.get_root(i)
        
        ans = len(set_1[par_1] & set_2[par_2])
        print(ans, end=" ")
    print()

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy

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

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

	def unite(self, a, b):
		ta = self.find(a)
		tb = self.find(b)
		if(ta == tb):
			return
		self._parent[ta] = tb # make b as a parent of a
			
	def check(self, a, b):
		return self.find(a) == self.find(b)
		
if __name__ == '__main__':
	N,K,L = map(int, input().split())
	uf1 = UnionFind(N)
	for _ in range(K):
		p,q = map(int, input().split())
		uf1.unite(p-1,q-1)
	uf2 = UnionFind(N)
	for _ in range(L):
		s,r = map(int, input().split())
		uf2.unite(s-1,r-1)
	from collections import defaultdict
	d = defaultdict(int)
	for i in range(N):
		d[(uf1.find(i), uf2.find(i))] += 1
	ans = []
	for i in range(N):
		ans.append( str(d[(uf1.find(i), uf2.find(i))]) )
	print(' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
import copy

class UnionFind:
	def __init__(self, N):
		self._parent = [i for i in range(N)]
		self._rank = [0 for i in range(N)]

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

	def unite(self, a, b):
		ta = self.find(a)
		tb = self.find(b)
		if(ta == tb):
			return
		
		if self._rank[ta] < self._rank[tb]:
			self._parent[ta] = tb # make b as a parent of a
		else:
			self._parent[tb] = ta # make a as a parent of b
			if(ta == tb):
				rank[ta] += 1
			
	def check(self, a, b):
		return self.find(a) == self.find(b)
		
if __name__ == '__main__':
	N,K,L = map(int, input().split())
	uf1 = UnionFind(N)
	for _ in range(K):
		p,q = map(int, input().split())
		uf1.unite(p-1,q-1)
	uf2 = UnionFind(N)
	for _ in range(L):
		s,r = map(int, input().split())
		uf2.unite(s-1,r-1)
	from collections import defaultdict
	d = defaultdict(int)
	for i in range(N):
		d[(uf1.find(i), uf2.find(i))] += 1
	ans = []
	for i in range(N):
		ans.append( str(d[(uf1.find(i), uf2.find(i))]) )
	print(' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
import copy

class UnionFind:
	def __init__(self, N):
		self._parent = [i for i in range(N)]
		self._rank = [0 for i in range(N)]

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

	def unite(self, a, b):
		ta = self.find(a)
		tb = self.find(b)
		if(ta == tb):
			return
		
		if self._rank[ta] < self._rank[tb]:
			self._parent[ta] = tb # make b as a parent of a
		else:
			self._parent[tb] = ta # make a as a parent of b
			if(ta == tb):
				rank[ta] += 1
			
	def check(self, a, b):
		return self.find(a) == self.find(b)
		
if __name__ == '__main__':
	N,K,L = map(int, input().split())
	ans = [0 for _ in range(N)]
	uf1 = UnionFind(N)
	for _ in range(K):
		p,q = map(int, input().split())
		uf1.unite(p-1,q-1)
	uf2 = UnionFind(N)
	for _ in range(L):
		s,r = map(int, input().split())
		uf2.unite(s-1,r-1)
	for i in range(N):
		for j in range(N):
			if uf1.check(i,j) and uf2.check(i,j):
				ans[i] += 1
	print(*ans)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import sys
N,K,L=map(int,raw_input().split())

# https://www.kumilog.net/entry/union-find#Python%E3%81%A7%E5%AE%9F%E8%A3%85
class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

ufR=UnionFind(N+1)
ufT=UnionFind(N+1)
for i in range(K):
    p,q=map(int,sys.stdin.readline().split())
    ufR.union(p,q)
for i in range(L):
    p,q=map(int,sys.stdin.readline().split())
    ufT.union(p,q)    
from collections import defaultdict
R=defaultdict(set)
T=defaultdict(set)
for i in range(1,N+1):
    R[ufR.find(i)].add(i)
    T[ufT.find(i)].add(i)

ans=[0]*(N+1)
for i in range(1,N+1):
    r=R[ufR.find(i)]
    t=T[ufT.find(i)]
    if len(r)==0 or len(t)==0: continue
    s=r&t
    for c in s:
        ans[c]=str(len(s))
    r-=s
    t-=s

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

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import sys
N,K,L=map(int,raw_input().split())

# https://www.kumilog.net/entry/union-find#Python%E3%81%A7%E5%AE%9F%E8%A3%85
class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

ufR=UnionFind(N+1)
ufT=UnionFind(N+1)
for i in range(K):
    p,q=map(int,sys.stdin.readline().split())
    ufR.union(p,q)
for i in range(L):
    p,q=map(int,sys.stdin.readline().split())
    ufT.union(p,q)    
from collections import defaultdict
R=defaultdict(set)
T=defaultdict(set)
for i in range(1,N+1):
    R[ufR.find(i)].add(i)
    T[ufT.find(i)].add(i)

ans={}
for i in range(1,N+1):
    r=R[ufR.find(i)]
    t=T[ufT.find(i)]
    if len(r)==0 or len(t)==0: continue
    s=r&t
    for c in s:
        ans[c]=len(s)
    r-=s
    t-=s
for i in range(1,N+1):
    print ans[i],
print("")

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8

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

# https://www.kumilog.net/entry/union-find#Python%E3%81%A7%E5%AE%9F%E8%A3%85
class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

ufR=UnionFind(N+1)
ufT=UnionFind(N+1)
for i in range(K):
    p,q=map(int,raw_input().split())
    ufR.union(p,q)
for i in range(L):
    p,q=map(int,raw_input().split())
    ufT.union(p,q)    
from collections import defaultdict
R=defaultdict(set)
T=defaultdict(set)
for i in range(1,N+1):
    R[ufR.find(i)].add(i)
    T[ufT.find(i)].add(i)

ans={}
for i in range(1,N+1):
    r=R[ufR.find(i)]
    t=T[ufT.find(i)]
    if len(r)==0 or len(t)==0: continue
    s=r&t
    for c in s:
        ans[c]=len(s)
    r-=s
    t-=s
for i in range(1,N+1):
    print ans[i],
print("")

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8

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

# https://www.kumilog.net/entry/union-find#Python%E3%81%A7%E5%AE%9F%E8%A3%85
class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

ufR=UnionFind(N+1)
ufT=UnionFind(N+1)
for i in range(K):
    p,q=map(int,raw_input().split())
    ufR.union(p,q)
for i in range(L):
    p,q=map(int,raw_input().split())
    ufT.union(p,q)    
from collections import defaultdict
R=defaultdict(set)
T=defaultdict(set)
for i in range(1,N+1):
    R[ufR.find(i)].add(i)
    T[ufT.find(i)].add(i)

ans={}
for i in range(1,N+1):
    r=R[ufR.find(i)]
    t=T[ufT.find(i)]
    s=r&t
    for c in s:
        ans[c]=len(s)
    r-=s
    t-=s
for i in range(1,N+1):
    print ans[i],
print("")

Submission status: Time Limit Exceeded

Solution code:
n,k,l=map(int,input().split())
c=[i+1 for i in range(n)]
t=[i+1 for i in range(n)]
i=[list(map(int,input().split())) for i in range(k)]
i.sort()
for p,q in i:
    if c[p-1]>c[q-1]:c[p-1]=c[q-1]
    else:c[q-1]=c[p-1]
i=[list(map(int,input().split())) for i in range(l)]
i.sort()
for r,s in i:
    if t[r-1]>t[s-1]:t[r-1]=t[s-1]
    else:t[r-1]=t[s-1]
a=[]
for i in range(n):
    x=0
    for j in range(n):
        if c[i]==c[j] and t[i]==t[j]:x+=1
    a.append(x)
print(' '.join(map(str,a)))

Submission status: Time Limit Exceeded

Solution code:
def find(ps,x):
    if ps[x]<0:
        return x
    else:
        ps[x]=find(ps,ps[x])
        return ps[x]
def unite(ps,x,y):
    x=find(ps,x)
    y=find(ps,y)
    if x==y:
        return False
    if ps[x]>ps[y]:
        x,y = y,x
    ps[x] += ps[y]
    ps[y] = x
    return True
def same(ps,x,y):
    return find(ps,x)==find(ps,y)

n,k,l = map(int,input().split())
tg = [-1]*(n+1)
rg = [-1]*(n+1)
for _ in range(k):
  p,q = map(int, input().split())
  unite(rg,p,q)
for _ in range(l):
  p,q = map(int, input().split())
  unite(tg,p,q)
ans = [1]*(n+1)
for i in range(1,n):
  for j in range(i+1,n+1):
    if same(rg,i,j) and same(tg,i,j):
      ans[i] += 1
      ans[j] += 1
print(" ".join(map(str,ans[1:])))