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:
from collections import defaultdict
N,K,L=list(input().split(" "))
N=int(N)
K=int(K)
L=int(L)

class deep_search:
    def __init__(self,n):
        self.n=n
        self.stack=[]
        self.mem=[]
        self.group={}
        self.dict=defaultdict(lambda:[])

    def unit(self,x,y):
        self.dict[x].append(y)
    def search(self):
        for v in range(1,self.n+1):
            if v not in self.mem:
                self.stack.append(v)
                self.mem.append(v)
                self.group[v]=v
                while self.stack!=[]:
                    w=self.stack.pop()
                    for ww in self.dict[w]:
                        if ww not in self.mem:
                            self.mem.append(ww)
                            self.group[ww]=v
                            self.stack.append(ww)
        return self.group
    
utl=deep_search(N)
utf=deep_search(N)

for i in range(K):
    p,q=map(int,list(input().split(" ")))
    utl.unit(p,q)
for i in range(L):
    r,s=map(int,list(input().split(" ")))
    utf.unit(r,s)
road_g=utl.search()
train_g=utf.search()
count=defaultdict(lambda:0)

for i in range(1,N+1):
    l=[road_g[i],train_g[i]]
    count[str(l)]+=1
for i in range(1,N+1):
    l=[road_g[i],train_g[i]]
    print(count[str(l)],end=" ")

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
n,k,l=map(int,input().split())
#union-find
par1=[-1]*(n+1)
par2=[-1]*(n+1)

def find1(x):
    if par1[x]<0:
        return x
    else:
        par1[x]=find1(par1[x])
        return par1[x]
def find2(x):
    if par2[x]<0:
        return x
    else:
        par2[x]=find2(par2[x])
        return par2[x]
def size1(x):
    return -par1[find1(x)]
def size2(x):
    return -par2[find2(x)]
def unite1(x,y):
    if find1(x)==find1(y):
        return False
    else:
        if size1(x)<size1(y):
            x,y=y,x
        X=find1(x)
        Y=find1(y)
        par1[X]-=size1(Y)
        par1[Y]=X
        return True
def unite2(x,y):
    if find2(x)==find2(y):
        return False
    else:
        if size2(x)<size2(y):
            x,y=y,x
        X=find2(x)
        Y=find2(y)
        par2[X]-=size2(Y)
        par2[Y]=X
        return True
def is_same1(x,y):
    return find1(x)==find1(y)
def is_same2(x,y):
    return find2(x)==find2(y)

for _ in range(k):
    p,q=map(int,input().split())
    unite1(p,q)
for _ in range(l):
    r,s=map(int,input().split())
    unite2(r,s)
ans=[0]*(n)
for i in range(1,n+1):
    for j in range(1,n+1):
        if is_same1(i,j) and is_same2(i,j):
            ans[i-1]+=1
print(*ans, sep=' ')

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
N,K,L=list(input().split(" "))
N=int(N)
K=int(K)
L=int(L)
road=defaultdict(lambda:[])
train=defaultdict(lambda:[])
for i in range(K):
    p,q=map(int,list(input().split(" ")))
    road[p].append(q)
for i in range(L):
    r,s=map(int,list(input().split(" ")))
    train[r].append(s)

def deep_search(dict):
    stack=[] 
    mem=[]
    group={}
    for v in list(dict):
        if v not in mem:
            stack.append(v)
            while stack!=[]:
                w=stack.pop()
                mem.append(w)
                group[w]=v
                for ww in dict[w]:
                    if ww not in mem:
                        mem.append(ww)
                        group[ww]=v
                        stack.append(ww)
    return group

road_g=deep_search(road)
train_g=deep_search(train)
count=defaultdict(lambda:0)
for i in range(1,N+1):
    if i in road_g.keys() and i in train_g.keys():
        l=[road_g[i],train_g[i]]
        count[str(l)]+=1
for i in range(1,N+1):
    if i in road_g.keys() and i in train_g.keys():
        l=[road_g[i],train_g[i]]
        print(count[str(l)],end=" ")
    else:
        print(1,end=" ")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

graphs = [[[] for _ in range(n)], [[] for _ in range(n)]]
cands = [set(), set()]
for _ in range(k):
    x, y = map(int, input().split())
    graphs[0][x - 1].append(y - 1)
    graphs[0][y - 1].append(x - 1)
    cands[0].add(x - 1)
for _ in range(l):
    x, y = map(int, input().split())
    graphs[1][x - 1].append(y - 1)
    graphs[1][y - 1].append(x - 1)
    cands[1].add(x - 1)

groups = [[], []]
groups_inv = [[-1] * n, [-1] * n]
def dfs(start, case, num):
    q = deque()
    q.append(start)
    used = {start}
    groups[case].append(used)
    groups_inv[case][start] = num
    while q:
        node = q.popleft()
        for to in graphs[case][node]:
            if to in used:
                continue
            q.append(to)
            used.add(to)
            groups_inv[case][to] = num

for i in range(2):
    count = 0
    for node in cands[i]:
        if groups_inv[i][node] == -1:
            dfs(node, i, count)
            count += 1

print(*[
    1 if groups_inv[0][i] == -1 or groups_inv[1][i] == -1
    else len(groups[0][groups_inv[0][i]] & groups[1][groups_inv[1][i]])
    for i in range(n)
])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

graphs = [[[] for _ in range(n)], [[] for _ in range(n)]]
cands = [set(), set()]
for _ in range(k):
    x, y = map(int, input().split())
    graphs[0][x - 1].append(y - 1)
    graphs[0][y - 1].append(x - 1)
    cands[0].add(x - 1)
for _ in range(l):
    x, y = map(int, input().split())
    graphs[1][x - 1].append(y - 1)
    graphs[1][y - 1].append(x - 1)
    cands[1].add(x - 1)

groups = [[], []]
groups_inv = [[-1] * n, [-1] * n]
def dfs(start, size, case, num):
    q = deque(maxlen=size)
    q.append(start)
    used = {start}
    groups[case].append(used)
    groups_inv[case][start] = num
    while q:
        node = q.popleft()
        for to in graphs[case][node]:
            if to in used:
                continue
            q.append(to)
            used.add(to)
            groups_inv[case][to] = num

for i in range(2):
    count = 0
    for node in cands[i]:
        if groups_inv[i][node] == -1:
            dfs(node, n, i, count)
            count += 1

print(*[
    1 if groups_inv[0][i] == -1 or groups_inv[1][i] == -1
    else len(groups[0][groups_inv[0][i]] & groups[1][groups_inv[1][i]])
    for i in range(n)
])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

graphs = [[[] for _ in range(n)], [[] for _ in range(n)]]
cands = [set(), set()]
for _ in range(k):
    x, y = map(int, input().split())
    graphs[0][x - 1].append(y - 1)
    graphs[0][y - 1].append(x - 1)
    cands[0].add(x - 1)
for _ in range(l):
    x, y = map(int, input().split())
    graphs[1][x - 1].append(y - 1)
    graphs[1][y - 1].append(x - 1)
    cands[1].add(x - 1)

groups = [[], []]
groups_inv = [[-1] * n, [-1] * n]
def dfs(start, size, type, num):
    q = deque(maxlen=size)
    q.append(start)
    used = {start}
    groups[type].append(used)
    groups_inv[type][start] = num
    while q:
        node = q.popleft()
        for to in graphs[i][node]:
            if to in used:
                continue
            q.append(to)
            used.add(to)
            groups_inv[type][to] = num

for i in range(2):
    count = 0
    for node in cands[i]:
        if groups_inv[i][node] == -1:
            dfs(node, n, i, count)
            count += 1

ret = [1] * n
ret_inv = [[-1] * n for _ in range(n)]
for i in range(n):
    if groups_inv[0][i] == -1 or groups_inv[1][i] == -1:
        continue
    if ret_inv[groups_inv[0][i]][groups_inv[1][i]] == -1:
        size = len(groups[0][groups_inv[0][i]] & groups[1][groups_inv[1][i]])
        ret_inv[groups_inv[0][i]][groups_inv[1][i]] = size
    ret[i] = size

print(*ret)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

graphs = [[[] for _ in range(n)], [[] for _ in range(n)]]
cands = [set(), set()]
for _ in range(k):
    x, y = map(int, input().split())
    graphs[0][x - 1].append(y - 1)
    graphs[0][y - 1].append(x - 1)
    cands[0].add(x - 1)
for _ in range(l):
    x, y = map(int, input().split())
    graphs[1][x - 1].append(y - 1)
    graphs[1][y - 1].append(x - 1)
    cands[1].add(x - 1)

groups = [[], []]
groups_inv = [[-1] * n, [-1] * n]
def dfs(start, size, type, num):
    q = deque(maxlen=size)
    q.append(start)
    used = {start}
    groups[type].append(used)
    groups_inv[type][start] = num
    while q:
        node = q.popleft()
        for to in graphs[i][node]:
            if to in used:
                continue
            q.append(to)
            used.add(to)
            groups_inv[type][to] = num

for i in range(2):
    count = 0
    for node in cands[i]:
        if groups_inv[i][node] == -1:
            dfs(node, n, i, count)
            count += 1

print(*[
    1 if groups_inv[0][i] == -1 or groups_inv[1][i] == -1
    else len(groups[0][groups_inv[0][i]] & groups[1][groups_inv[1][i]])
    for i in range(n)
])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)


def unite(par, i, j):
    j = get_par(par, j)
    par[j] = get_par(par, i)

def get_par(par, p):
    while par[p] != p:
        p = par[p]
    return par[p]

n,k,l = map(int, input().split())
pq = []
road = [i for i in range(n+1)]
rcnt = [set([i]) for i in range(n+1)]
rail = [i for i in range(n+1)]
acnt = [set([i]) for i in range(n+1)]
for i in range(k):
    p,q = map(int,input().split())
    pq.append((p,q))
    aa = get_par(road, p)
    bb = get_par(road, q)
    if aa == bb:
        continue
    # unite
    if aa < bb:
        road[bb] = aa
        rcnt[aa] |= rcnt[bb]
    else:
        road[aa] = bb
        rcnt[bb] |= rcnt[aa]

rs = []
for i in range(l):
    p,q = map(int,input().split())
    rs.append((p,q))
    aa = get_par(rail, p)
    bb = get_par(rail, q)
    if aa == bb:
        continue
    # unite
    if aa < bb:
        rail[bb] = aa
        acnt[aa] |= acnt[bb]
        # acnt[aa] += acnt[bb]
    else:
        rail[aa] = bb
        acnt[bb] |= acnt[aa]

ans = [0 for _ in range(n+1)]
for i in range(1,n+1):
    if ans[i] == 0:
        r = get_par(road, i)
        l = get_par(rail, i)
        # print(rcnt[r], acnt[l])
        cnt = 0
        for j in rcnt[r] | acnt[l]:
            if j in rcnt[r] and j in acnt[l]:
                cnt += 1
        for j in rcnt[r] & acnt[l]:
            ans[j] = cnt

print(*ans[1:])
# print(acnt)
# print(rcnt)

Submission status: Time Limit Exceeded

Solution code:
def main():
    class UnionFind():
        # 作りたい要素数nで初期化
    # 使用するインスタンス変数の初期化
            def __init__(self, n):
                self.n = n
                # root[x]<0ならそのノードが根かつその値が木の要素数
                # rootノードでその木の要素数を記録する
                self.root = [-1]*(n+1)
                # 木をくっつける時にアンバランスにならないように調整する
                self.rnk = [0]*(n+1)      
            # ノードxのrootノードを見つける
            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):
                # 入力ノードのrootノードを見つける
                x = self.Find_Root(x)
                y = self.Find_Root(y)
                # すでに同じ木に属していた場合
                if(x == y):
                    return 
                # 違う木に属していた場合rnkを見てくっつける方を決める
                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
                    # rnkが同じ（深さに差がない場合）は1増やす
                    if(self.rnk[x] == self.rnk[y]):
                        self.rnk[y] += 1
            # xとyが同じグループに属するか判断
            def isSameGroup(self, x, y):
                return self.Find_Root(x) == self.Find_Root(y)     
            # ノードxが属する木のサイズを返す
            def Count(self, x):
                return -self.root[self.Find_Root(x)]      
    #abc049D
    ii = lambda : int(input())
    mi = lambda : map(int,input().split())
    li = lambda : list(map(int,input().split()))
    n,k,l = mi()
    road = UnionFind(n)
    train = UnionFind(n)
    for i in range(k):
        p,q = mi()
        road.Unite(p,q)
    for i in range(l):
        p,q = mi()
        train.Unite(p,q)
    lis = []
    for i in range(1,n+1):
        a = road.Find_Root(i)
        b = train.Find_Root(i)
        lis.append([a,b,i])
    inf = 10 ** 6
    lis.append([inf,inf,inf])
    lis.sort()
    lis2 = [0] * n
    tmp = 1
    for i in range(1,n+1):
        if (lis[i-1][0] == lis[i][0]) and (lis[i-1][1] == lis[i][1]):
            tmp += 1
        else:
            lis2[i-1] = tmp
            tmp = 1
    lis3 = [] 
    tmp = 0
    for i in range(n-1,-1,-1):
        if lis2[i] != 0:
           lis3.append([[lis[i][2]],lis2[i]])
           tmp = lis2[i]
        else:
           lis3.append([[lis[i][2]],tmp])
    lis3.sort()
    lis4 = []
    for i in range(n):
        lis4.append(lis3[i][1])
    print(*lis4)
       
main()

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 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())
p= [list(map(int, input().split())) for i in range(k)]
r = [list(map(int, input().split())) for i in range(l)]
uf1=UnionFind(n)
uf2=UnionFind(n)
for i in range(k):
    uf1.union(p[i][0]-1,p[i][1]-1)

for i in range(l):
    uf2.union(r[i][0]-1,r[i][1]-1)
ans=[1]*n

for i in range(n):
    for j in range(n):
        if i==j:
            continue
        if uf2.same(i,j):
            if uf1.same(i,j):
                ans[i]+=1

print(*ans)

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 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())
p= [list(map(int, input().split())) for i in range(k)]
r = [list(map(int, input().split())) for i in range(l)]
uf1=UnionFind(n)
uf2=UnionFind(n)
for i in range(k):
    uf1.union(p[i][0]-1,p[i][1]-1)

for i in range(l):
    uf2.union(r[i][0]-1,r[i][1]-1)
ans=[]

for i in range(n):
    a=set(uf1.members(i))&set(uf2.members(i))
    a=len(list(a))
    ans.append(a)
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 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())
p= [list(map(int, input().split())) for i in range(k)]
r = [list(map(int, input().split())) for i in range(l)]
uf1=UnionFind(n)
uf2=UnionFind(n)
for i in range(k):
    uf1.union(p[i][0]-1,p[i][1]-1)

for i in range(l):
    uf2.union(r[i][0]-1,r[i][1]-1)
ans=[]

for i in range(n):
    a=set(uf1.members(i))&set(uf2.members(i))
    a=len(list(a))
    ans.append(a)
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
#uniontree
#D - 連結 / Connectivity
#https://atcoder.jp/contests/abc049/tasks/arc065_b
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]


ans = []
n, k, l = list(map(int,input().split()))

p = UnionFind(n)
r = UnionFind(n)
for _ in range(k):
    a,b = list(map(int,input().split()))
    p.union(a-1,b-1)
for _ in range(l):
    c, d = list(map(int,input().split()))
    r.union(c-1,d-1)
for i in range(n):
    s = p.members(i)
    t = r.members(i)
    #print(s,t)
    count = 0
    for i in s:
        if i in t:
            count += 1
    ans.append(count)

#print(''.join(ans))、なぜか通らない、おそらくstrに変更しないと不可の模様
print(' '.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
#uniontree
#D - 連結 / Connectivity
#https://atcoder.jp/contests/abc049/tasks/arc065_b

class UnionFind():
   # 作りたい要素数nで初期化
   # 使用するインスタンス変数の初期化
   def __init__(self, n):
       self.n = n
       # root[x]<0ならそのノードが根かつその値が木の要素数
       # rootノードでその木の要素数を記録する、集合扱い
       self.root = [-1]*(n+1)
       # 木をくっつける時にアンバランスにならないように調整するためのrnk、累積和
       self.rnk = [0]*(n+1)
   # ノードxのrootノードを見つける
   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):
       # 入力ノードのrootノードを見つける
       x = self.Find_Root(x)
       y = self.Find_Root(y)
       # すでに同じ木に属していた場合
       if(x == y):
           return
       # 違う木に属していた場合rnkを見てくっつける方を決める、大きい方に巻かれるスタイル
       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
           # rnkが同じ（深さに差がない場合）は1増やす
           if(self.rnk[x] == self.rnk[y]):
               self.rnk[y] += 1
   # xとyが同じグループに属するか判断
   def isSameGroup(self, x, y):
       return self.Find_Root(x) == self.Find_Root(y)
   # ノードxが属する木のサイズを返す
   def Count(self, x):
       return -self.root[self.Find_Root(x)]#マイナスいる？

    
n, k, l = list(map(int,input().split()))
h1 = UnionFind(n)
h2 = UnionFind(n)
for i in range(k):
    p, q = list(map(int,input().split()))
    h1.Unite(p,q)
for j in range(l):
    r, s = list(map(int,input().split()))
    h2.Unite(r,s)
    
ans = [-1]*n#i=jのときdaoubleカウントされるので
for i in range(1,n+1):
    #count = 0
    #for j in range(1,n+1):TLE
    for j in range(i,n+1):
        if h1.isSameGroup(i,j) and h2.isSameGroup(i,j):
            #count += 1
            ans[i-1] += 1
            ans[j-1] += 1
    #ans.append(str(count))
print(' '.join(map(str, ans)))#joinするものはstrにする

Submission status: Time Limit Exceeded

Solution code:
#uniontree
#D - 連結 / Connectivity
#https://atcoder.jp/contests/abc049/tasks/arc065_b

class UnionFind():
   # 作りたい要素数nで初期化
   # 使用するインスタンス変数の初期化
   def __init__(self, n):
       self.n = n
       # root[x]<0ならそのノードが根かつその値が木の要素数
       # rootノードでその木の要素数を記録する、集合扱い
       self.root = [-1]*(n+1)
       # 木をくっつける時にアンバランスにならないように調整するためのrnk、累積和
       self.rnk = [0]*(n+1)
   # ノードxのrootノードを見つける
   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):
       # 入力ノードのrootノードを見つける
       x = self.Find_Root(x)
       y = self.Find_Root(y)
       # すでに同じ木に属していた場合
       if(x == y):
           return
       # 違う木に属していた場合rnkを見てくっつける方を決める、大きい方に巻かれるスタイル
       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
           # rnkが同じ（深さに差がない場合）は1増やす
           if(self.rnk[x] == self.rnk[y]):
               self.rnk[y] += 1
   # xとyが同じグループに属するか判断
   def isSameGroup(self, x, y):
       return self.Find_Root(x) == self.Find_Root(y)
   # ノードxが属する木のサイズを返す
   def Count(self, x):
       return -self.root[self.Find_Root(x)]#マイナスいる？

    
n, k, l = list(map(int,input().split()))
h1 = UnionFind(n)
h2 = UnionFind(n)
for i in range(k):
    p, q = list(map(int,input().split()))
    h1.Unite(p,q)
for j in range(l):
    r, s = list(map(int,input().split()))
    h2.Unite(r,s)
    
ans = []
for i in range(1,n+1):
    count = 0
    for j in range(1,n+1):
        if h1.isSameGroup(i,j) and h2.isSameGroup(i,j):
            count += 1
    ans.append(str(count))
print(' '.join(ans))#joinするものはstrにする

Submission status: Time Limit Exceeded

Solution code:
class UnionFindTree:
    def __init__(self):
        self.p = {}
        self.rank = {}

    def make(self, x):
        self.p[x] = x
        self.rank[x] = 0

    def find(self, x):
        if x in self.p:
            if self.p[x] != x:
                # 経路圧縮
                self.p[x] = self.find(self.p[x])
            return self.p[x]
        return None

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

    def unite(self, x, y):
        return self._unite(self.find(x), self.find(y))

    def _unite(self, x, y):
        if self.rank[x] < self.rank[y]:
            self.p[x] = y
            return y
        else:
            self.p[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            return x


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

utf1 = UnionFindTree()
utf2 = UnionFindTree()
for i in range(N):
    utf1.make(i+1)
    utf2.make(i+1)

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

ans = [0]*N
for i in range(1, N+1):
    for j in range(1, N+1):
        a = utf1.same(i, j)
        b = utf2.same(i, j)
        if a and a == b:
            ans[i-1] += 1
print(" ".join([str(_) for _ in ans]))

Submission status: Time Limit Exceeded

Solution code:
class UnionFind():
    def __init__(self,n):
        self.n = n
        self.parents = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
    def find(self,x):
        root = x
        while self.parents[root] != root:
            root = self.parents[root]
        while self.parents[x] != root:
            parent = self.parents[x]
            self.parents[x] = root
            x = parent
        return root
    def unite(self,x,y):
        xroot = self.find(x)
        yroot = self.find(y)
        if xroot == yroot:
            return
        xrank = self.rank[xroot]
        yrank = self.rank[yroot]
        if xrank < yrank:
            self.parents[xroot] = yroot
        elif xrank == yrank:
            self.parents[yroot] = xroot
            self.rank[yroot] += 1
        else:
            self.parents[yroot] = xroot
            
N,K,L=map(int,input().split())
ufroad = UnionFind(N)
uftrain = UnionFind(N)

for i in range(K):
    p,q = map(int,input().split())
    ufroad.unite(p-1,q-1)
for i in range(L):
    r,s = map(int,input().split())
    uftrain.unite(r-1,s-1)
uflist=[]
for i in range(N):
    uflist.append((ufroad.find(i), uftrain.find(i)))
counter={}
for i in range(N):
  if uflist[i] not in counter.keys():
    counter[uflist[i]]=1
  else:
    counter[uflist[i]]+=1
print(' '.join(map(str, [counter[uflist[i]] for i in range(N)])))

Submission status: Time Limit Exceeded

Solution code:
class UnionFind():
    def __init__(self,n):
        self.n = n
        self.parents = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
    def find(self,x):
        root = x
        while self.parents[root] != root:
            root = self.parents[root]
        while self.parents[x] != root:
            parent = self.parents[x]
            self.parents[x] = root
            x = parent
        return root
    def unite(self,x,y):
        xroot = self.find(x)
        yroot = self.find(y)
        if xroot == yroot:
            return
        xrank = self.rank[xroot]
        yrank = self.rank[yroot]
        if xrank < yrank:
            self.parents[xroot] = yroot
        elif xrank == yrank:
            self.parents[yroot] = xroot
            self.rank[yroot] += 1
        else:
            self.parents[yroot] = xroot
            
N,K,L=map(int,input().split())
ufroad = UnionFind(N)
uftrain = UnionFind(N)

for i in range(K):
    p,q = map(int,input().split())
    ufroad.unite(p-1,q-1)
for i in range(L):
    r,s = map(int,input().split())
    uftrain.unite(r-1,s-1)
uflist=[]
for i in range(N):
    uflist.append((ufroad.find(i), uftrain.find(i)))
ans=[uflist.count(uflist[i]) for i in range(N)]
print(' '.join(map(str, ans)))