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: Accepted

Solution code:
from collections import defaultdict

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


class UnionFind(object):

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

    def is_same(self, a, b):
        return self.root(a) == self.root(b)

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

load_uf = UnionFind(N)
rail_uf = UnionFind(N)

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

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

ans = []
d = defaultdict(int)
for i in range(N):
    lp = load_uf.root(i)
    rp = rail_uf.root(i)
    d[lp, rp] += 1

for i in range(N):
    lp = load_uf.par[i]
    rp = rail_uf.par[i]
    if i == N-1:
        print(d[lp, rp])
    else:
        print(d[lp, rp], end=' ')

#     print(rd[rp])
#     print(ld[lp])
#     ans.append(len(ld[lp] & rd[rp]))
# print(str(ans).replace(',', '')[1:-1])

Submission status: Accepted

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

def root(x):
    #if x != parent[x]: x = parent[x] = root(parent[x])
    if x != parent[x]: parent[x] = 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 i 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: Accepted

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
    def ra(self):
        return self.par

n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
uf2=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())
    uf2.unite(a-1,b-1)

q1=uf.ra()
q2=uf2.ra()
d={}
for i in range(n):
    while 1:
        if q1[i]!=q1[q1[i]]:
            q1[i]=q1[q1[i]]
        else:
            break
    while 1:
        if q2[i]!=q2[q2[i]]:
            q2[i]=q2[q2[i]]
        else:
            break

for i in range(n):
    if (q1[i],q2[i]) in d:
        d[(q1[i],q2[i])]+=1
    else:
        d[(q1[i],q2[i])]=1
for i in range(n):
    print d[(q1[i],q2[i])],

Submission status: Accepted

Solution code:
# -*- 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
    def ra(self):
        return self.par

n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
uf2=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())
    uf2.unite(a-1,b-1)

q1=uf.ra()
q2=uf2.ra()
d={}
for i in range(n):
    while 1:
        if q1[i]!=q1[q1[i]]:
            q1[i]=q1[q1[i]]
        else:
            break
    while 1:
        if q2[i]!=q2[q2[i]]:
            q2[i]=q2[q2[i]]
        else:
            break

for i in range(n):
    if (q1[i],q2[i]) in d:
        d[(q1[i],q2[i])]+=1
    else:
        d[(q1[i],q2[i])]=1
for i in range(n):
    print d[(q1[i],q2[i])],

Submission status: Accepted

Solution code:
from collections import defaultdict
class UnionFind:
    def __init__(self,size):
        self.parent=range(size)
        self.tree_num=size
        self.tree_w=[1]*size
        self.rank=[0]*size

    def findset(self,x):
        if self.parent[x]==x:
            return x
        else:
            self.parent[x]=self.findset(self.parent[x])
            return self.parent[x]

    def unite(self,x,y):
        x=self.findset(x)
        y=self.findset(y)
        if x==y:
            return
        if self.rank[x]<self.rank[y]:
            self.parent[x]=y
            self.tree_num-=1
            self.tree_w[y]+=self.tree_w[x]
        else:
            self.parent[y]=x
            self.tree_num-=1
            self.tree_w[x]+=self.tree_w[y]
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def same(self,x,y):
        if self.findset(x)==self.findset(y):
            return True
        else:
            return False

    def tree_number(self):
        return self.tree_num

    def tree_weight(self,x):
        return self.tree_w[self.findset(x)]

n,k,l=map(int,raw_input().split())
uf1=UnionFind(n)
uf2=UnionFind(n)
for i in xrange(k):
    p,q=map(int,raw_input().split())
    p-=1;q-=1
    uf1.unite(p,q)
for i in xrange(l):
    p,q=map(int,raw_input().split())
    p-=1;q-=1
    uf2.unite(p,q)
cnt=defaultdict(int)
for i in xrange(n):
    cnt[(uf1.findset(i),uf2.findset(i))]+=1
ans=[0]*n
for i in xrange(n):
    ans[i]+=cnt[(uf1.findset(i),uf2.findset(i))]
print " ".join(map(str,ans))

Submission status: Accepted

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

def root(x):
    if x != parent[x]: parent[x] = 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 i 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: Accepted

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

def root(x):
    if x == parent[x]: return x
    parent[x] = root(parent[x])
    return parent[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 i 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: Accepted

Solution code:

def f(m, r):
    connmap = [[] for _ in range(m + 1)]
    for _ in range(r):
        a, b = map(int, input().split())
        connmap[a].append(b)
        connmap[b].append(a)
    group = [0] * (m + 1)
    num = 0
    for i in range(1, m + 1):
        if group[i] > 0:
            continue
        num += 1
        group[i] = num
        for j in connmap[i]:
            group[j] = num
        bfs = connmap[i]
        while len(bfs) > 0:
            tmp = []
            for j in bfs:
                for k in connmap[j]:
                    if group[k] > 0:
                        continue
                    group[k] = num
                    tmp.append(k)
            bfs = tmp
    return group

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

road = f(n, k)
rail = f(n, l)

count = {}

for i in range(1, n + 1):
    key = '{0} {1}'.format(road[i], rail[i])
    if key in count:
        count[key] += 1
    else:
        count[key] = 1
    
for i in range(1, n + 1):
    key = '{0} {1}'.format(road[i], rail[i])
    print(count[key], end=' ' if i < n else '')
print()

Submission status: Accepted

Solution code:
#!/usr/bin/env pypy3

import collections


class UnionFind(object):

    def __init__(self, number_of_nodes):
        self.par = list(range(number_of_nodes))
        self.rank = [0] * number_of_nodes

    def root(self, node):
        if self.par[node] == node:
            return node
        else:
            r = self.root(self.par[node])
            self.par[node] = r
            return r

    def in_the_same_set(self, node1, node2):
        return self.root(node1) == self.root(node2)

    def unite(self, node1, node2):
        x = self.root(node1)
        y = self.root(node2)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1


def main():
    n, k, l = (int(x) for x in input().split())
    uf_roads = UnionFind(n)
    for _ in range(k):
        p, q = (int(x) - 1 for x in input().split())
        uf_roads.unite(p, q)
    uf_rails = UnionFind(n)
    for _ in range(l):
        r, s = (int(x) - 1 for x in input().split())
        uf_rails.unite(r, s)
    ctr = collections.Counter((uf_roads.root(i), uf_rails.root(i))
                              for i in range(n))
    ans = [ctr[(uf_roads.root(i), uf_rails.root(i))] for i in range(n)]
    print(" ".join(str(a) for a in ans))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict


class UnionFind3:
    def __init__(self, size):
        self.table = [-1 for _ in range(size)]

    def find(self, x):
        while self.table[x] >= 0:
            x = self.table[x]
        return x

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2


n, k, l = map(int, input().split())
ufd, ufr = UnionFind3(n), UnionFind3(n)
for _ in range(k):
    p, q = map(int, input().split())
    ufd.union(p - 1, q - 1)
for _ in range(l):
    r, s = map(int, input().split())
    ufr.union(r - 1, s - 1)
d = defaultdict(int)
for i in range(n):
    d[ufd.root(i), ufr.root(i)] += 1
print(*(d[ufd.root(i), ufr.root(i)] for i in range(n)))

Submission status: Accepted

Solution code:
import collections

class UnionFind:
    def __init__(self, n):
        self._id = list(range(n))
        self._sz = [1] * n

    def _root(self, i):
        j = i
        while (j != self._id[j]):
            self._id[j] = self._id[self._id[j]]
            j = self._id[j]
        return j

    def find(self, p, q):
        return self._root(p) == self._root(q)

    def union(self, p, q):
        i = self._root(p)
        j = self._root(q)
        if (self._sz[i] < self._sz[j]):
            self._id[i] = j
            self._sz[j] += self._sz[i]
        else:
            self._id[j] = i
            self._sz[i] += self._sz[j]

n, k, l = [int(x) for x in input().split()]
pqs = set(tuple(int(x) - 1 for x in input().split()) for _ in range(k))
rss = set(tuple(int(x) - 1 for x in input().split()) for _ in range(l))

road = UnionFind(n)
for pq in pqs:
    road.union(*pq)

rail = UnionFind(n)
for rs in rss:
    rail.union(*rs)

roadrail = [(road._root(i), rail._root(i)) for i in range(n)]
cnt = collections.Counter(roadrail)

print(' '.join([str(cnt[r]) for r in roadrail]))

Submission status: Accepted

Solution code:
class UnionFind:
 
    def __init__(self, size):
        # 負の値はルート (集合の代表) で集合の個数
        # 正の値は次の要素を表す
        self.size = size
        self.table = [-1 for _ in range(size)]
 
    def find(self, x):
        # 集合の代表を求める
        children = []
        while self.table[x] >= 0:
            children.append(x)
            x = self.table[x]
        for c in children:
            self.table[c] = x
        return x
 
    def union(self, x, y):
        # 併合
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] >= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
        return self.table[s1]
 
n,k,l= map(int, input().split())
road = UnionFind(n+1)
train = UnionFind(n+1)
for i in range(k):
    p,q = map(int, input().split())
    road.union(p, q)
for i in range(l):
    p,q = map(int, input().split())
    train.union(p,q)
import collections
d = collections.defaultdict(int)
for i in range(1,n+1):
    r = road.find(i)
    t = train.find(i)
    d[(r,t)] += 1
res = [d[(road.find(i), train.find(i))] for i in range(1,n+1)]

print(*res, sep=' ')

Submission status: Accepted

Solution code:
# マージO(n)かかっちゃう
class union_find:
	def __init__(self, size):
		# 負の値はルート (集合の代表) で集合の個数
		# 正の値は次の要素を表す
		self.size=size
		self.table = [-1 for _ in range(size)]
		self.num=[0 for i in range(size)]

	# 集合の代表を求める
	def find(self, x):
		if self.table[x] < 0:
			return x
		else:
			# 経路の圧縮
			self.table[x] = self.find(self.table[x])
			return(self.table[x])

	# 併合
	def unite(self, x, y):
		s1 = self.find(x)
		s2 = self.find(y)
		if s1 != s2:
			if self.table[s1] <= self.table[s2]:
				# 小さいほうが個数が多い
				self.table[s1] += self.table[s2]
				self.table[s2] = s1
			else:
				self.table[s2] += self.table[s1]
				self.table[s1] = s2
			return(True)
		return(False)

	def definite(self):
		for i in range(self.size):
			self.num[i]=self.find(i)
		return(True)


N,K,L=list(map(int,input().split()))
road=union_find(N)
rail=union_find(N)

for i in range(K):
	a=list(map(int,input().split()))
	road.unite(a[0]-1,a[1]-1)

for i in range(L):
	a=list(map(int,input().split()))
	rail.unite(a[0]-1,a[1]-1)

road.definite()
rail.definite()

dic={}
# print(road.num,rail.num)

for i in range(N):
	key=str(road.num[i])+":"+str(rail.num[i])
	if key in dic:
		dic[key].append(i)
	else:
		dic[key]=[i]

# print(dic)
res=[0 for i in range(N)]
for i in dic.values():
	l=len(i)
	for j in i:
		res[j]=l

for i in res:
	print(i,end=" ")
print("")

Submission status: Accepted

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

road_parent = list(range(N))
road_rank = [0] * N
train_parent = list(range(N))
train_rank = [0] * N

def Find(parent, i):
	if parent[i] == i:
		return i
	else:
		parent[i] = Find(parent, parent[i])
		return parent[i]

def Union(parent, rank, i, j):
	i_root = Find(parent, i)
	j_root = Find(parent, j)
	if rank[i_root] > rank[j_root]:
		parent[j_root] = i_root
	elif rank[i_root] < rank[j_root]:
		parent[i_root] = j_root
	elif i_root != j_root:
		parent[j_root] = i_root
		rank[i_root] += 1

for cnt in range(K):
	i,j = map(int, input().split())
	Union(road_parent, road_rank, i-1, j-1)

for cnt in range(L):
	i,j = map(int, input().split())
	Union(train_parent, train_rank, i-1, j-1)

from collections import defaultdict

counter = defaultdict(int)
for i in range(N):
	counter[(Find(road_parent, i), Find(train_parent, i))] += 1

print(' '.join(str(counter[(Find(road_parent, i), Find(train_parent, i))]) for i in range(N)))

Submission status: Accepted

Solution code:
from sys import exit, setrecursionlimit
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

class union_find:
  def __init__(self, n): self.par = [-1]*n
  def __repr__(self): return "union_find({0})".format(self.par)
  def unite(self, x, y):
    if self.root(x) != self.root(y):
      self.par[self.root(x)] = y
  def root(self, x):
    if self.par[x] == -1: return x
    else:
      self.par[x] = self.root(self.par[x])
      return self.par[x]
  def same(self, x, y): return self.root(x) == self.root(y)

setrecursionlimit(1000000)

(N, K, L) = reads()

rail = union_find(N)
road = union_find(N)

for _ in range(K):
  (p, q) = reads()
  (p, q) = (p-1, q-1)
  road.unite(p, q)

for _ in range(L):
  (p, q) = reads()
  (p, q) = (p-1, q-1)
  rail.unite(p, q)

d = defaultdict(int)
for i in range(N):
  d[road.root(i), rail.root(i)] += 1


results = (d[road.root(i), rail.root(i)] for i in range(N))
print(" ".join(str(n) for n in results))

Submission status: Runtime Error

Solution code:
from collections import *
from heapq import *
from itertools import *
import sys
import copy
from bisect import *
sys.setrecursionlimit(10000000)
sys.
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 rdfs(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: Runtime Error

Solution code:
from collections import *
from heapq import *
from itertools import *
import sys
import copy
from bisect import *


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 rdfs(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: Runtime Error

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(k):
  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: Runtime Error

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(k):
  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: Runtime Error

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
# 連結判定
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
c = Counter(zip(uf_road,uf_railroad))
res = [c[(i, j)] for i, j in zip(uf_road, uf_railroad)]
print(*res)

Submission status: Runtime Error

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)
                q.put(target)
                #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]:
                railroad[target].remove(now_node)
                q.put(target)
        idx_railroad += 1
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: Runtime Error

Solution code:
#temp

class Uf:
    def __init__(self, N):
        self.p = list(range(N))
        self.rank = [0] * N
        self.size = [1] * N

    def root(self, x):
        if self.p[x] != x:
            self.p[x] = self.root(self.p[x])

        return self.p[x]

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

    def unite(self, x, y):
        u = self.root(x)
        v = self.root(y)

        if u == v: return

        if self.rank[u] < self.rank[v]:
            self.p[u] = v
            self.size[v] += self.size[u]
            self.size[u] = 0
        else:
            self.p[v] = u
            self.size[u] += self.size[v]
            self.size[v] = 0

            if self.rank[u] == self.rank[v]:
                self.rank[u] += 1

    def count(self, x):
        return self.size[self.root(x)]

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

p=[]
q=[]
r=[]
s=[]

for i in range(K):
    a,b=map(int,input().split())
    p.append(a-1)
    q.append(b-1)

for  i in range(L):
    a,b=map(int,input().split())
    r.append(a-1)
    s.append(b-1)

road=Uf()
train=Uf()
for i in range(K):
    road.unite(p[i],q[i])
for i in range(L):
    train.unite(r[i],s[i])

ans=[1]*N

for i in range(N):
    r=road.count()

Submission status: Runtime Error

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

def uft_root(g, a):
	if g[a] < 0:
		return a
	g[a] = uft_root(g, g[a])
	return g[a]

def uft_size(g, a):
	return -g[uft_root(g, a)]

def uft_merge(g, a, b):
	a, b = uft_root(g, a), uft_root(g, b)
	if a == b:
		return
	size_a, size_b = uft_size(g, a), uft_size(g, b)
	if size_a < size_b:
		a, b = b, a
		size_a, size_b = size_b, size_a
	g[a] -= size_b
	g[b] = a

g_pq = [[] for _ in range(N)]
for p, q in PQ:
	p, q = p - 1, q - 1
	g_pq[p] += [q]
	g_pq[q] += [p]

g_rs = [[] for _ in range(N)]
for r, s in RS:
	r, s = r - 1, s - 1
	g_rs[r] += [s]
	g_rs[s] += [r]

def dfs(v, g, uft, visited):
	if visited[v]:
		return
	visited[v] = True
	for n in g[v]:
		if visited[n]:
			continue
		uft_merge(uft, v, n)
		dfs(n, g, uft, visited)

visited_pq = [False] * N
visited_rs = [False] * N
uft_pq = [-1] * N
uft_rs = [-1] * N

for n in range(N):
	dfs(n, g_pq, uft_pq, visited_pq)
	dfs(n, g_rs, uft_rs, visited_rs)

group_pq, group_rs = {}, {}
for n in range(N):
	root_pq = uft_root(uft_pq, n)
	if not root_pq in group_pq:
		group_pq[root_pq] = {n}
	else:
		group_pq[root_pq] |= {n}
	root_rs = uft_root(uft_rs, n)
	if not root_rs in group_rs:
		group_rs[root_rs] = {n}
	else:
		group_rs[root_rs] |= {n}

for n in range(N):
	print(len(group_pq[uft_root(uft_pq, n)] & group_rs[uft_root(uft_rs, n)]), "", end="")
print()