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: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        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

    def group_num(self):
        return self.grp



n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
ans=['1']*n
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
for i in range(l):
    a,b=map(int,raw_input().split())
    if uf.same(a-1,b-1):
        ans[a-1]='2'
        ans[b-1]='2'
print ' '.join(ans)

Submission status: Wrong Answer

Solution code:
n, k, l = map(int, raw_input().split())

def root(x):
    if x != parent[x]: x = parent[x] = root(parent[x])
    return x
def unite(x, y):
    px = root(x)
    py = root(y)
    if px < py:
        parent[py] = px
    else:
        parent[px] = py

parent = range(n)
for i in xrange(k):
    p, q = map(int, raw_input().split())
    unite(p-1, q-1)
parent1 = parent
for i in xrange(n):root(i)

parent = range(n)
for j in xrange(l):
    r, s = map(int, raw_input().split())
    unite(r-1, s-1)
parent2 = parent
for i in xrange(n):root(i)

dic = {}
for p1, p2 in zip(parent1, parent2):
    dic[p1, p2] = dic.get((p1, p2), 0) + 1

ans = [dic[p1, p2] for p1, p2 in zip(parent1, parent2)]
print " ".join(map(str, ans))

Submission status: Wrong Answer

Solution code:
n, k, l = map(int, raw_input().split())

def root(x):
    if x != parent[x]: x = parent[x] = root(parent[x])
    return x
def unite(x, y):
    px = root(x)
    py = root(y)
    if px < py:
        parent[py] = px
    else:
        parent[px] = py

parent = range(n)
for i in xrange(k):
    p, q = map(int, raw_input().split())
    unite(p-1, q-1)
parent1 = parent

parent = range(n)
for j in xrange(l):
    r, s = map(int, raw_input().split())
    unite(r-1, s-1)
parent2 = parent

dic = {}
for p1, p2 in zip(parent1, parent2):
    dic[p1, p2] = dic.get((p1, p2), 0) + 1

ans = [dic[p1, p2] for p1, p2 in zip(parent1, parent2)]
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 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())
road = UnionFind(N)
train = UnionFind(N)
ans = []
for i in range(K):
    p, q = map(int, input().split())
    road.union(p-1, q-1)
for i in range(L):
    r, s = map(int, input().split())
    train.union(r-1, s-1)
for i in range(N):
    ans.append(len(set(road.members(i)) & set(train.members(i))))
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from heapq import *
from itertools import *
import sys
import copy
from bisect import *
sys.setrecursionlimit(10**9)
N,K,L = map(int,input().split())
RoLists=[[] for i in range(N)]
RaLists=[[] for _ in range(N)]
for i in range(K):
    p,q=map(int,input().split())
    RoLists[p-1].append(q-1)
    RoLists[q-1].append(p-1)
for j in range(L):
    p,q=map(int,input().split())
    RaLists[p-1].append(q-1)
    RaLists[q-1].append(p-1)
def dfs(g, v, visited):
    if not visited[v]:
        yield v
        visited[v] = True
        for w in iter(g[v]):
            for x in dfs(g, w, visited):
                yield x
def r_dfs(g,v):
    visited = [False] * N
    for x in dfs(g, v, visited):
        yield x
for i in range(N):
    ans=0
    for h in r_dfs(RoLists, i):
        for j in r_dfs(RaLists, i):
            if j == h:
                ans+=1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from heapq import *
from itertools import *
import sys
import copy
from bisect import *
sys.setrecursionlimit(10**9)
N,K,L = map(int,input().split())
RoLists=[[] for i in range(N)]
RaLists=[[] for _ in range(N)]
for i in range(K):
    p,q=map(int,input().split())
    RoLists[p-1].append(q-1)
    RoLists[q-1].append(p-1)
for j in range(L):
    p,q=map(int,input().split())
    RaLists[p-1].append(q-1)
    RaLists[q-1].append(p-1)
def dfs(g, v, visited):
    if not visited[v]:
        yield v
        visited[v] = True
        for w in iter(g[v]):
            for x in dfs(g, w, visited):
                yield x
def r_dfs(g,v):
    visited = [False] * N
    for x in dfs(g, v, visited):
        yield x
for i in range(N):
    ans=0
    for h in r_dfs(RoLists,i):
        for j in r_dfs(RaLists,i):
            if j == h:
                ans+=1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from heapq import *
from itertools import *
import sys
import copy
from bisect import *
sys.setrecursionlimit(10**9)
N,K,L = map(int,input().split())
RoLists=[[] for i in range(N)]
RaLists=[[] for _ in range(N)]
for i in range(K):
    p,q=map(int,input().split())
    RoLists[p-1].append(q-1)
    RoLists[q-1].append(p-1)
for j in range(L):
    p,q=map(int,input().split())
    RaLists[p-1].append(q-1)
    RaLists[q-1].append(p-1)
def dfs(g, v, visited):
    if not visited[v]:
        yield v
        visited[v] = True
        for w in iter(g[v]):
            for x in dfs(g, w, visited):
                yield x
def r_dfs(g,v):
    visited = [False] * N
    for x in dfs(g, v, visited):
        yield x
for i in range(N):
    ans=0
    for h in r_dfs(RoLists,i):
        for i in r_dfs(RaLists,i):
            if i == h:
                ans+=1
    print(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 unite(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()}

n,k,l=map(int,input().split())
uf1=UnionFind(n)
uf2=UnionFind(n)
for _ in range(k):
  u,v=map(int,input().split())
  uf1.unite(u-1,v-1)
for _ in range(l):
  u,v=map(int,input().split())
  uf2.unite(u-1,v-1)
ans=[]
for i in range(n):
  x=set(uf1.members(i))&set(uf2.members(i))
  ans.append(len(x))
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import queue

N, K, L = map(int, input().split())
PQ = [tuple(map(int, input().split())) for _ in range(K)]
RS = [tuple(map(int, input().split())) for _ in range(L)]

road = [set() for _ in range(N)]
railroad = [set() for _ in range(N)]
for p, q in PQ:
    road[p - 1].add(q - 1)
    road[q - 1].add(p - 1)
for r, s in RS:
    railroad[r - 1].add(s - 1)
    railroad[s - 1].add(r - 1)

uf_road = [0] * N
uf_railroad = [0] * N
idx_road = 1
idx_railroad = 1
mita1 = set()
mita2 = set()
# 連結判定
for i in range(N):
    if uf_road[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            for target in road[now_node]:
                if target not in mita1:
                    q.put(target)
                    # mita1.add(target)
            mita1 = mita1 | road[now_node]
        idx_road += 1
    if uf_railroad[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            for target in railroad[now_node]:
                if target not in mita2:
                    q.put(target)
                    # mita2.add(target)
            mita2 = mita2 | railroad[now_node]
        idx_railroad += 1
dic = Counter(zip(uf_road,uf_railroad))
res = [dic[(i, j)] for i, j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import queue

N, K, L = map(int, input().split())
PQ = [tuple(map(int, input().split())) for _ in range(K)]
RS = [tuple(map(int, input().split())) for _ in range(L)]

road = [set() for _ in range(N)]
railroad = [set() for _ in range(N)]
for p, q in PQ:
    road[p - 1].add(q - 1)
    road[q - 1].add(p - 1)
for r, s in RS:
    railroad[r - 1].add(s - 1)
    railroad[s - 1].add(r - 1)

uf_road = [0] * N
uf_railroad = [0] * N
idx_road = 1
idx_railroad = 1
mita1 = set()
mita2 = set()
# 連結判定
for i in range(N):
    if uf_road[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            # target_set = set(road[now_node]) - mita1
            for target in road[now_node]:
                # if uf_road[target] == -1:
                if target not in mita1:
                    # road[target].remove(now_node)
                    q.put(target)
                    mita1.add(target)
            #road[now_node] = []
        idx_road += 1
    if uf_railroad[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            # target_set = set(railroad[now_node]) - mita2
            for target in railroad[now_node]:
                # if uf_railroad[target] == -1:
                if target not in mita2:
                    # railroad[target].remove(now_node)
                    q.put(target)
                    mita2.add(target)
            #railroad[now_node] = []
        idx_railroad += 1
dic = Counter(zip(uf_road,uf_railroad))
res = [dic[(i, j)] for i, j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import queue

N, K, L = map(int, input().split())
PQ = [tuple(map(int, input().split())) for _ in range(K)]
RS = [tuple(map(int, input().split())) for _ in range(L)]

road = [set() for _ in range(N)]
railroad = [set() for _ in range(N)]
for p, q in PQ:
    road[p - 1].add(q - 1)
    road[q - 1].add(p - 1)
for r, s in RS:
    railroad[r - 1].add(s - 1)
    railroad[s - 1].add(r - 1)

uf_road = [0] * N
uf_railroad = [0] * N
idx_road = 1
idx_railroad = 1
mita1 = set()
mita2 = set()
# 連結判定
for i in range(N):
    if uf_road[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            # target_set = set(road[now_node]) - mita1
            for target in road[now_node]:
                # if uf_road[target] == -1:
                if target not in mita1:
                    road[target].remove(now_node)
                    q.put(target)
                    mita1.add(target)
            #road[now_node] = []
        idx_road += 1
    if uf_railroad[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            # target_set = set(railroad[now_node]) - mita2
            for target in railroad[now_node]:
                # if uf_railroad[target] == -1:
                if target not in mita2:
                    railroad[target].remove(now_node)
                    q.put(target)
                    mita2.add(target)
            #railroad[now_node] = []
        idx_railroad += 1
dic = Counter(zip(uf_road,uf_railroad))
res = [dic[(i, j)] for i, j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import queue

N, K, L = map(int, input().split())
PQ = [tuple(map(int, input().split())) for _ in range(K)]
RS = [tuple(map(int, input().split())) for _ in range(L)]

road = [set() for _ in range(N)]
railroad = [set() for _ in range(N)]
for p, q in PQ:
    road[p - 1].add(q - 1)
    road[q - 1].add(p - 1)
for r, s in RS:
    railroad[r - 1].add(s - 1)
    railroad[s - 1].add(r - 1)

uf_road = [-1] * N
uf_railroad = [-1] * N
idx_road = 1
idx_railroad = 1
mita1 = set()
mita2 = set()
# 連結判定
for i in range(N):
    if uf_road[i] == -1:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            target_set = set(road[now_node]) - mita1
            for target in target_set:
                road[target].remove(now_node)
                if uf_road[target] == -1:
                    q.put(target)
                    mita1.add(target)
            #road[now_node] = []
        idx_road += 1
    if uf_railroad[i] == -1:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            target_set = set(railroad[now_node]) - mita2
            for target in target_set:
                railroad[target].remove(now_node)
                if uf_railroad[target] == -1:
                    q.put(target)
                    mita2.add(target)
            #railroad[now_node] = []
        idx_railroad += 1
dic = Counter(zip(uf_road,uf_railroad))
res = [dic[(i, j)] for i, j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
from collections import Counter
import queue

N, K, L = map(int, input().split())
PQ = [tuple(map(int, input().split())) for _ in range(K)]
RS = [tuple(map(int, input().split())) for _ in range(L)]

road = [set() for _ in range(N)]
railroad = [set() for _ in range(N)]
for p, q in PQ:
    road[p - 1].add(q - 1)
    road[q - 1].add(p - 1)
for r, s in RS:
    railroad[r - 1].add(s - 1)
    railroad[s - 1].add(r - 1)

uf_road = [-1] * N
uf_railroad = [-1] * N
idx_road = 1
idx_railroad = 1
# 連結判定
for i in range(N):
    if uf_road[i] == -1:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            for target in road[now_node]:
                road[target].remove(now_node)
                if uf_road[target] == -1:
                    q.put(target)
                    uf_road[target] = 0
            #road[now_node] = []
        idx_road += 1
    if uf_railroad[i] == -1:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            for target in railroad[now_node]:
                railroad[target].remove(now_node)
                if uf_railroad[target] == -1:
                    q.put(target)
                    uf_railroad[target] = 0
            #railroad[now_node] = []
        idx_railroad += 1
dic = Counter(zip(uf_road,uf_railroad))
res = [dic[(i, j)] for i, j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
import queue
N, K, L = map(int,input().split())
PQ = [tuple(map(int,input().split())) for _ in range(K)]
RS = [tuple(map(int,input().split())) for _ in range(L)]

road = [[] for _ in range(N)]
railroad = [[] for _ in range(N)]
for p,q in PQ:
    road[p-1].append(q-1)
    road[q-1].append(p-1)
for r,s in RS:
    railroad[r-1].append(s-1)
    railroad[s-1].append(r-1)

uf_road = [0]*N
uf_railroad = [0]*N
idx_road = 1
idx_railroad = 1
# 連結判定
for i in range(N):
    if uf_road[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            for target in road[now_node]:
                road[target].remove(now_node)
                if uf_road[target]==0:
                    q.put(target)
            road[now_node] = []
        idx_road += 1
    if uf_railroad[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            for target in railroad[now_node]:
                railroad[target].remove(now_node)
                if uf_railroad[target]==0:
                    q.put(target)
            railroad[now_node] = []
        idx_railroad += 1
dic = dd(int)
#print(uf_road)
#print(uf_railroad)
for i,j in zip(uf_road, uf_railroad):
    dic[(i,j)] += 1
res = [dic[(i,j)] for i,j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
import queue
N, K, L = map(int,input().split())
PQ = [tuple(map(int,input().split())) for _ in range(K)]
RS = [tuple(map(int,input().split())) for _ in range(L)]

road = [[] for _ in range(N)]
railroad = [[] for _ in range(N)]
for p,q in PQ:
    road[p-1].append(q-1)
    road[q-1].append(p-1)
for r,s in RS:
    railroad[r-1].append(s-1)
    railroad[s-1].append(r-1)

uf_road = [0]*N
uf_railroad = [0]*N
idx_road = 1
idx_railroad = 1
# 連結判定
for i in range(N):
    if uf_road[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            for target in road[now_node]:
                if uf_road[target] == 0:
                    q.put(target)
        idx_road += 1
    if uf_railroad[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            for target in railroad[now_node]:
                if uf_railroad[target] == 0:
                    q.put(target)
        idx_railroad += 1
# print(uf_road)
# print(uf_railroad)
dic = dd(int)
for i,j in zip(uf_road, uf_railroad):
    dic[(i,j)] += 1
res = [dic[(i,j)] for i,j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
import queue
N, K, L = map(int,input().split())
PQ = [tuple(map(int,input().split())) for _ in range(K)]
RS = [tuple(map(int,input().split())) for _ in range(L)]

road = [[] for _ in range(N)]
railroad = [[] for _ in range(N)]
for p,q in PQ:
    road[p-1].append(q-1)
    road[q-1].append(p-1)
for r,s in RS:
    railroad[r-1].append(s-1)
    railroad[s-1].append(r-1)

uf_road = [0]*N
uf_railroad = [0]*N
idx_road = 1
idx_railroad = 1
# 連結判定
for i in range(N):
    if uf_road[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_road[now_node] = idx_road
            target_list = road[now_node]
            for target in target_list:
                if uf_road[target] == 0:
                    q.put(target)
        idx_road += 1
    if uf_railroad[i] == 0:
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            now_node = q.get()
            uf_railroad[now_node] = idx_railroad
            target_list = railroad[now_node]
            for target in target_list:
                if uf_railroad[target] == 0:
                    q.put(target)
        idx_railroad += 1
# print(uf_road)
# print(uf_railroad)
dic = dd(int)
for i,j in zip(uf_road, uf_railroad):
    dic[(i,j)] += 1
res = [dic[(uf_road[i], uf_railroad[i])] for i in range(N)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
# AtCoder Regular Contest 065
# D - 連結 / Connectivity
# https://atcoder.jp/contests/arc065/tasks/arc065_b
import sys
from collections import defaultdict

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
        self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        self.parent[x] = y

def main():
    N, *KL = map(int, input().split())
    uf = [UnionFind(N) for _ in range(2)]
    for i in range(2):
        for j in range(KL[i]):
            p, q = map(int, input().split())
            uf[i].union(p-1, q-1)

    d = defaultdict(int)
    for i in range(N):
        d[(uf[0].find(i), uf[1].find(i))] += 1

    # for i in range(N):
    #     print(d[(uf[0].find(i), uf[1].find(i))], end = " ")
    # print("")
    
    print(" ".join([str(d[(uf[0].find(i), uf[1].find(i))]) for i in range(N)]))

if __name__ == "__main__":
    sys.setrecursionlimit(10**6)
    main()

Submission status: Time Limit Exceeded

Solution code:
# AtCoder Regular Contest 065
# D - 連結 / Connectivity
# https://atcoder.jp/contests/arc065/tasks/arc065_b
import sys
from collections import defaultdict

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
        self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        self.parent[x] = y

def main():
    N, *KL = map(int, input().split())
    uf = [UnionFind(N) for _ in range(2)]
    for i in range(2):
        for j in range(KL[i]):
            p, q = map(int, input().split())
            uf[i].union(p-1, q-1)

    d = defaultdict(int)
    for i in range(N):
        d[(uf[0].find(i), uf[1].find(i))] += 1

    for i in range(N):
        print(d[(uf[0].find(i), uf[1].find(i))], end = " ")
    print("")

if __name__ == "__main__":
    sys.setrecursionlimit(10**6)
    main()

Submission status: Time Limit Exceeded

Solution code:
class Unionfind:

    __slots__ = ['parents','sizes']

    def __init__(self, n):
        self.parents = list(range(n))
        self.sizes = [1]*n

    def root(self, x):
        if self.parents[x] == x:
            return x
        else:
            root_x = self.root(self.parents[x])
            self.parents[x] = root_x
            return root_x

    def unite(self, x, y):
        x = self.root(x); y = self.root(y)
        if x == y:
            return
        if self.sizes[x] < self.sizes[y]:
            x, y = y, x
        self.sizes[x] += self.sizes[y]
        self.parents[y] = x

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

    # 集合自体の数 ({1,2}, {3}, {4} : kind -> 3)
    def kind(self):
        for v in range(N):
            self.root(v)
        return len(list(set(self.parents)))

    # xが属する集合の要素の数　({1,2,3} : size(2) -> 3)
    def size(self, x):
        self.sizes[x] = self.sizes[self.root(x)]
        return self.sizes[x]

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

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

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

ans_list = []

r = [set() for _ in range(N)]
t = [set() for _ in range(N)]
for i in range(N):
    road.parents[i] = road.root(i)
    r[road.parents[i]].add(i)
    train.parents[i] = train.root(i)
    t[train.parents[i]].add(i)

ans_list = []

for i in range(N):
    ans = len(r[road.parents[i]] & t[train.parents[i]])
    ans_list.append(ans)

print(*ans_list)

Submission status: Time Limit Exceeded

Solution code:
class Unionfind:

    __slots__ = ['parents','sizes']

    def __init__(self, n):
        self.parents = list(range(n))
        self.sizes = [1]*n

    def root(self, x):
        if self.parents[x] == x:
            return x
        else:
            root_x = self.root(self.parents[x])
            self.parents[x] = root_x
            return root_x

    def unite(self, x, y):
        x = self.root(x); y = self.root(y)
        if x == y:
            return
        if self.sizes[x] < self.sizes[y]:
            x, y = y, x
        self.sizes[x] += self.sizes[y]
        self.parents[y] = x

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

    # 集合自体の数 ({1,2}, {3}, {4} : kind -> 3)
    def kind(self):
        for v in range(N):
            self.root(v)
        return len(list(set(self.parents)))

    # xが属する集合の要素の数　({1,2,3} : size(2) -> 3)
    def size(self, x):
        self.sizes[x] = self.sizes[self.root(x)]
        return self.sizes[x]

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

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

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

ans_list = []

r = [set() for _ in range(N)]
t = [set() for _ in range(N)]
for i in range(N):
    r[road.root(i)].add(i)
    t[train.root(i)].add(i)

ans_list = []

for i in range(N):
    ans = len(r[road.root(i)] & t[train.root(i)])
    ans_list.append(ans)

print(*ans_list)

Submission status: Time Limit Exceeded

Solution code:
def main():

    import sys
    input = sys.stdin.readline
    from collections import defaultdict

    class Unionfind:

        __slots__ = ['parents','sizes']

        def __init__(self, n):
            self.parents = list(range(n))
            self.sizes = [1]*n

        def root(self, x):
            if self.parents[x] == x:
                return x
            else:
                root_x = self.root(self.parents[x])
                self.parents[x] = root_x
                return root_x

        def unite(self, x, y):
            x = self.root(x); y = self.root(y)
            if x == y:
                return
            if self.sizes[x] < self.sizes[y]:
                x, y = y, x
            self.sizes[x] += self.sizes[y]
            self.parents[y] = x

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

        # 集合自体の数 ({1,2}, {3}, {4} : kind -> 3)
        def kind(self):
            for v in range(N):
                self.root(v)
            return len(list(set(self.parents)))

        # xが属する集合の要素の数　({1,2,3} : size(2) -> 3)
        def size(self, x):
            self.sizes[x] = self.sizes[self.root(x)]
            return self.sizes[x]

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

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

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

    ans_list = []

    r = defaultdict(set)
    t = defaultdict(set)
    for i in range(N):
        r[road.root(i)].add(i)
        t[train.root(i)].add(i)

    ans_list = []

    for i in range(N):
        ans = len(r[road.root(i)] & t[train.root(i)])
        ans_list.append(ans)

    print(*ans_list)

if __name__ == "__main__":
    main()