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

Solution code:

import sys
input = sys.stdin.readline

road = {}
train = {}
node_all = set()
node_seen = set()
road_belong_group = []
train_belong_group = []
road_group = {}
train_group = {}

def dfs_road(t_node, group_num):
    global node_seen, road_group, road_belong_group
    node_seen.add(t_node)
    road_belong_group[t_node] = group_num
    road_group[group_num].add(t_node)
    next_nodes = set(road[t_node]) - node_seen
    if not list(next_nodes):
        return
    else:
        for next in next_nodes:
            dfs_road(next, group_num)

def dfs_train(t_node, group_num):
    global node_seen, train_group, train_belong_group
    node_seen.add(t_node)
    train_belong_group[t_node] = group_num
    train_group[group_num].add(t_node)
    next_nodes = set(train[t_node]) - node_seen
    if not list(next_nodes):
        return
    else:
        for next in next_nodes:
            dfs_train(next, group_num)

def main():
    global road, train, node_seen, road_group, train_group, node_all, road_belong_group,train_belong_group
    # 入力
    n, k, l = map(int, input().split())
    node_all = set([i for i in range(1, n + 1)])
    road = {e:[] for e in range(1, n + 1)}
    road_belong_group = [0] * (n + 1)
    train_belong_group = [0] * (n + 1)
    road_belong_group[0] = -1
    train_belong_group[0] = -1

    for _ in range(k):
        p, q = map(int, input().split())
        road[p].append(q)
        road[q].append(p)
    train = {e:[] for e in range(1, n + 1)}
    for _ in range(l):
        s, t = map(int, input().split())
        train[s].append(t)
        train[t].append(s)

    # 処理
    ## 道路
    road_group[-1] = set()
    train_group[-1] = set()

    group_num_road = 1
    while list(node_all - node_seen):
        node_remain = road_belong_group.index(0)
        if node_remain == 0:
            node_remain = 1
        if not road[node_remain]:
            road_belong_group[node_remain] = -1
            node_seen.add(node_remain)
            continue
        road_group[group_num_road] = set()
        dfs_road(node_remain, group_num_road)
        group_num_road += 1


    ## 鉄道
    group_num_train = 1
    node_seen = set()
    while list(node_all - node_seen):
        node_remain = train_belong_group.index(0)
        if node_remain == 0:
            node_remain = 1
        if not train[node_remain]:
            train_belong_group[node_remain] = -1
            node_seen.add(node_remain)
            continue
        train_group[group_num_train] = set()
        dfs_train(node_remain, group_num_train)
        group_num_train += 1

    # 出力
    for i in range(1, n + 1):
        linked_city = len(road_group[road_belong_group[i]] & train_group[train_belong_group[i]] )
        if linked_city == 0:
            linked_city += 1
        print(linked_city, end = ' ')


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
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]

      
from collections import defaultdict
 
N, K, L = map(int, input().split())

# 道路のUnionFind
uf1 = UnionFind(N)
for i in range(K):
    p, q = map(int, input().split())
    uf1.union(p - 1, q - 1)
 
# 鉄道のUnionFind
uf2 = UnionFind(N)
for i in range(L):
    r, s = map(int, input().split())
    uf2.union(r - 1, s - 1)
 
# 道路と鉄道の連結の組み合わせ（根のペアのカウント）
c = {}
for i in range(N):
    if (uf1.find(i), uf2.find(i)) in c:
      c[(uf1.find(i), uf2.find(i))] += 1
    else:
      c[(uf1.find(i), uf2.find(i))] = 1      

# 回答を出力
for i in range(N):
    print(c[(uf1.find(i), uf2.find(i))])

Submission status: Runtime Error

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


class UnionFind:

    def __init__(self, n):
        self.n = n
        # access m-th node by index `m`, not `m - 1`
        self.roots = [i for i in range(n + 1)]
        self.ranks = [0 for _ in range(n + 1)]
        self.group_sizes = [1 for _ in range(n + 1)]

    def find_root(self, node):
        root_node = self.roots[node]
        if node == root_node:
            return root_node
        else:
            new_root_node = self.find_root(root_node)
            self.roots[node] = new_root_node  # reduction
            return root_node

    def union(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        if one_root == other_root:
            return
        if self.ranks[one_root] < self.ranks[other_root]:
            self.roots[one_root] = other_root
            self.group_sizes[other_root] += self.group_sizes[one_root]
        else:
            self.roots[other_root] = one_root
            self.group_sizes[one_root] += self.group_sizes[other_root]
            if self.ranks[one_root] == self.ranks[other_root]:
                self.ranks[other_root] += 1

    def is_same_group(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        return one_root == other_root

    def group_size(self, node):
        root_node = self.find_root(node)
        return self.group_sizes[root_node]


def main():
    N, K, L = list(map(int, input().split(' ')))
    road_tree = UnionFind(N)
    for _ in range(K):
        p, q = list(map(int, input().split(' ')))
        road_tree.union(p, q)
    road_train_tree = UnionFind(N)
    for _ in range(L):
        r, s = list(map(int, input().split(' ')))
        if not road_tree.is_same_group(r, s):
            continue
        road_train_tree.union(r, s)
    answer = ' '.join([str(road_train_tree.group_size(node)) for node in range(1, N + 1)])
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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


class UnionFind:

    def __init__(self, n):
        self.n = n
        # access m-th node by index `m`, not `m - 1`
        self.roots = [i for i in range(n + 1)]
        self.ranks = [0 for _ in range(n + 1)]
        self.group_sizes = [1 for _ in range(n + 1)]

    def find_root(self, node):
        root_node = self.roots[node]
        if node == root_node:
            return root_node
        else:
            new_root_node = self.find_root(root_node)
            self.roots[node] = new_root_node  # reduction
            return root_node

    def union(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        if one_root == other_root:
            return
        if self.ranks[one_root] < self.ranks[other_root]:
            self.roots[one_root] = other_root
            self.group_sizes[other_root] += self.group_sizes[one_root]
        else:
            self.roots[other_root] = one_root
            self.group_sizes[one_root] += self.group_sizes[other_root]
            if self.ranks[one_root] == self.ranks[other_root]:
                self.ranks[other_root] += 1

    def is_same_group(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        return one_root == other_root

    def group_size(self, node):
        root_node = self.find_root(node)
        return self.group_sizes[root_node]


def main():
    N, K, L = list(map(int, input().split(' ')))
    road_tree = UnionFind(N)
    for _ in range(K):
        p, q = list(map(int, input().split(' ')))
        road_tree.union(p, q)
    road_train_tree = UnionFind(N)
    for _ in range(L):
        r, s = list(map(int, input().split(' ')))
        if not road_tree.is_same_group(r, s):
            continue
        road_train_tree.union(r, s)
    answer = ' '.join([str(road_train_tree.group_size(node)) for node in range(1, N + 1)])
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
class UnionFind:

    def __init__(self, n):
        self.n = n
        # access m-th node by index `m`, not `m - 1`
        self.roots = [i for i in range(n + 1)]
        self.ranks = [0 for _ in range(n + 1)]
        self.group_sizes = [1 for _ in range(n + 1)]

    def find_root(self, node):
        root_node = self.roots[node]
        if node == root_node:
            return root_node
        else:
            new_root_node = self.find_root(root_node)
            self.roots[node] = new_root_node  # reduction
            return root_node

    def union(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        if one_root == other_root:
            return
        if self.ranks[one_root] < self.ranks[other_root]:
            self.roots[one_root] = other_root
            self.group_sizes[other_root] += self.group_sizes[one_root]
        else:
            self.roots[other_root] = one_root
            self.group_sizes[one_root] += self.group_sizes[other_root]
            if self.ranks[one_root] == self.ranks[other_root]:
                self.ranks[other_root] += 1

    def is_same_group(self, one, other):
        one_root = self.find_root(one)
        other_root = self.find_root(other)
        return one_root == other_root

    def group_size(self, node):
        root_node = self.find_root(node)
        return self.group_sizes[root_node]


def main():
    N, K, L = list(map(int, input().split(' ')))
    road_tree = UnionFind(N)
    for _ in range(K):
        p, q = list(map(int, input().split(' ')))
        road_tree.union(p, q)
    road_train_tree = UnionFind(N)
    for _ in range(L):
        r, s = list(map(int, input().split(' ')))
        if not road_tree.is_same_group(r, s):
            continue
        road_train_tree.union(r, s)
    answer = ' '.join([str(road_train_tree.group_size(node)) for node in range(1, N + 1)])
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


class UnionFind:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.parents = [-1] * n_nodes

    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 get_size(self, x):
        return -self.parents[self.find(x)]

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

    def get_parent_list(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def get_members(self, x):
        parent = self.find(x)
        return [i for i in range(self.n_nodes) if self.find(i) == parent]

    def get_members_dict(self):
        return {par: self.get_members(par) for par in self.get_parent_list()}


def main():
    N, K, L = map(int, input().split())
    tree_road = UnionFind(N)
    tree_subway = UnionFind(N)

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

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

    d1 = tree_road.get_members_dict()
    d2 = tree_subway.get_members_dict()

    for i in range(N):
        m1 = set(d1[i])
        m2 = set(d2[i])
        print(len(m1 & m2), end=" ")


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
"""
in1 = '7 4 4'
in2 = ['1 2', '2 3', '2 5', '6 7', '3 5', '4 5', '3 4', '6 7']
N, K, L = map(int, in1.split())
pqrs = []
for idx1 in range(K + L):
    temp0, temp1 = map(int, in2[idx1].split())
    pqrs.append([temp0, temp1])
"""
N, K, L = map(int, input().split())
pqrs = []
for idx1 in range(K + L):
    temp0, temp1 = map(int, input().sprit())
    pqrs.append([temp0, temp1])

def makeTree(a):
    aT = list(range(N + 1))
    for p, q in a:
        rootp     = getRoot(aT, p)
        rootq     = getRoot(aT, q)
        thisRoot  = max(rootp, rootq, q)
        aT[p]     = thisRoot
        aT[q]     = thisRoot
        aT[rootp] = thisRoot
        aT[rootq] = thisRoot
    return aT

def getRoot(a,i):
    if a[i] == i:
        return i
    else:
        a[i] = getRoot(a, a[i])
        return a[i]

MTree = makeTree(pqrs[0:K])
TTree = makeTree(pqrs[K:])

aRet = []
dRet = {}
for idx1 in range(1, N + 1):
    Comb = (getRoot(MTree, idx1), getRoot(TTree, idx1))
    aRet.append(Comb)
    if Comb in dRet:
        dRet[Comb] += 1
    else:
        dRet[Comb] = 1

print(" ".join([str(dRet[_]) for _ in aRet]))

Submission status: Runtime Error

Solution code:
"""
in1 = '7 4 4'
in2 = ['1 2', '2 3', '2 5', '6 7', '3 5', '4 5', '3 4', '6 7']
N, K, L = [int(_) for _ in in1.split()]
pqrs = [[int(_) for _ in _.split()] for _ in in2]
"""
N, K, L = map(int, input().split())
pqrs = [[0] * 2] * N
for idx1 in range(N):
    temp = input().sprit()
    pqrs[idx1][0] = temp[0]
    pqrs[idx1][1] = temp[1]

def makeTree(a):
    aT = list(range(N + 1))
    for p, q in a:
        rootp     = getRoot(aT, p)
        rootq     = getRoot(aT, q)
        thisRoot  = max(rootp, rootq, q)
        aT[p]     = thisRoot
        aT[q]     = thisRoot
        aT[rootp] = thisRoot
        aT[rootq] = thisRoot
    return aT

def getRoot(a,i):
    if a[i] == i:
        return i
    else:
        a[i] = getRoot(a, a[i])
        return a[i]

MTree = makeTree(pqrs[0:K])
TTree = makeTree(pqrs[K:])

aRet = []
dRet = {}
for idx1 in range(1, N + 1):
    Comb = (getRoot(MTree, idx1), getRoot(TTree, idx1))
    aRet.append(Comb)
    if Comb in dRet:
        dRet[Comb] += 1
    else:
        dRet[Comb] = 1

print(" ".join([str(dRet[_]) for _ in aRet]))

Submission status: Runtime Error

Solution code:
"""
in1 = '7 4 4'
in2 = ['1 2', '2 3', '2 5', '6 7', '3 5', '4 5', '3 4', '6 7']
N, K, L = [int(_) for _ in in1.split()]
pqrs = [[int(_) for _ in _.split()] for _ in in2]
"""
N, K, L = [int(idx1) for idx1 in input().split()]
pqrs = [[int(idx1) for idx1 in item1.split()] for item1 in input()]

def makeTree(a):
    aT = list(range(N + 1))
    for p, q in a:
        rootp     = getRoot(aT, p)
        rootq     = getRoot(aT, q)
        thisRoot  = max(rootp, rootq, q)
        aT[p]     = thisRoot
        aT[q]     = thisRoot
        aT[rootp] = thisRoot
        aT[rootq] = thisRoot
    return aT

def getRoot(a,i):
    if a[i] == i:
        return i
    else:
        a[i] = getRoot(a, a[i])
        return a[i]

MTree = makeTree(pqrs[0:K])
TTree = makeTree(pqrs[K:])

aRet = []
dRet = {}
for idx1 in range(1, N + 1):
    Comb = (getRoot(MTree, idx1), getRoot(TTree, idx1))
    aRet.append(Comb)
    if Comb in dRet:
        dRet[Comb] += 1
    else:
        dRet[Comb] = 1

print(" ".join([str(dRet[_]) for _ in aRet]))

Submission status: Runtime Error

Solution code:
"""
in1 = '7 4 4'
in2 = ['1 2', '2 3', '2 5', '6 7', '3 5', '4 5', '3 4', '6 7']
N, K, L = [int(_) for _ in in1.split()]
pqrs = [[int(_) for _ in _.split()] for _ in in2]
"""
N, K, L = [int(_) for _ in input().split()]
pqrs = [[int(_) for _ in _.split()] for _ in input()]

def makeTree(a):
    aT = list(range(N + 1))
    for p, q in a:
        rootp     = getRoot(aT, p)
        rootq     = getRoot(aT, q)
        thisRoot  = max(rootp, rootq, q)
        aT[p]     = thisRoot
        aT[q]     = thisRoot
        aT[rootp] = thisRoot
        aT[rootq] = thisRoot
    return aT

def getRoot(a,i):
    if a[i] == i:
        return i
    else:
        a[i] = getRoot(a, a[i])
        return a[i]

MTree = makeTree(pqrs[0:K])
TTree = makeTree(pqrs[K:])

aRet = []
dRet = {}
for idx1 in range(1, N + 1):
    Comb = (getRoot(MTree, idx1), getRoot(TTree, idx1))
    aRet.append(Comb)
    if Comb in dRet:
        dRet[Comb] += 1
    else:
        dRet[Comb] = 1

print(" ".join([str(dRet[_]) for _ in aRet]))

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

class UnionFind:
    def __init__(self, n):
        self.state = [-1] * n
        self.size_table = [1<<i for i in range(n)]
        # cntはグループ数
        # self.cnt = n

    def root(self, u):
        v = self.state[u]
        if v < 0: return u
        self.state[u] = res = self.root(v)
        return res

    def merge(self, u, v):
        ru = self.root(u)
        rv = self.root(v)
        if ru == rv: return
        du = self.state[ru]
        dv = self.state[rv]
        if du > dv: ru, rv = rv, ru
        if du == dv: self.state[ru] -= 1
        self.state[rv] = ru
        # self.cnt -= 1
        self.size_table[ru] |= self.size_table[rv]
        self.size_table[rv]=0
        return

    # グループの要素数
    def size(self, u):
        return self.size_table[self.root(u)]

def popcnt(a):
    res=0
    while a:
        res+=a&1
        a>>=1
    return res

def main():
    n,k,l=MI()
    road=UnionFind(n)
    train=UnionFind(n)
    for _ in range(k):
        u,v=MI1()
        road.merge(u,v)
    for _ in range(l):
        u,v=MI1()
        train.merge(u,v)
    ans=[popcnt(road.size(i)&train.size(i)) for i in range(n)]
    print(*ans)

main()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

class UnionFind:
    def __init__(self, n):
        self.state = [-1] * n
        self.size_table = [1<<i for i in range(n)]
        # cntはグループ数
        # self.cnt = n

    def root(self, u):
        v = self.state[u]
        if v < 0: return u
        self.state[u] = res = self.root(v)
        return res

    def merge(self, u, v):
        ru = self.root(u)
        rv = self.root(v)
        if ru == rv: return
        du = self.state[ru]
        dv = self.state[rv]
        if du > dv: ru, rv = rv, ru
        if du == dv: self.state[ru] -= 1
        self.state[rv] = ru
        # self.cnt -= 1
        self.size_table[ru] |= self.size_table[rv]
        self.size_table[rv]=0
        return

    # グループの要素数
    def size(self, u):
        return self.size_table[self.root(u)]

def main():
    n,k,l=MI()
    road=UnionFind(n)
    train=UnionFind(n)
    for _ in range(k):
        u,v=MI1()
        road.merge(u,v)
    for _ in range(l):
        u,v=MI1()
        train.merge(u,v)
    ans=[bin(road.size(i)&train.size(i)).count("1") for i in range(n)]
    print(*ans)

main()

Submission status: Runtime Error

Solution code:
import sys
from collections import defaultdict
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())
uf_k = UnionFind(n)
uf_l = UnionFind(n)
for i in range(k):
    p, q = map(int, input().split())
    uf_k.union(p - 1, q - 1)
for i in range(l):
    r, s = map(int, input().split())
    uf_l.union(r - 1, s - 1)
d = defaultdict(int)
for i in range(n):
    d[uf_k.find(i), uf_l.find(i)] += 1
print(*d[uf_k.find(i), uf_l.find(i)] for i in range(n))

Submission status: Runtime Error

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

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.d = [-1] * n

    def find(self, x):
        if self.d[x] < 0:
            return x
        else:
            self.d[x] = self.find(self.d[x])
            return self.d[x]
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return False
        else:
            if self.d[x] > self.d[y]:
                x, y = y, x
            self.d[x] += self.d[y]
            self.d[y] = x
            return True

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


    def size(self, x):
        return -self.d[self.find(x)]


n, k, l = map(int, input().split())
uf = UnionFind(n)
for i in range(k):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf.unite(p, q)
ans = [1] * n
for i in range(l):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    if uf.same(r, s) == True:
# print(uf.d)
print(' '.join(map(str, ans)))

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
A = [[int(i) for i in input().split()] for _ in range(H)]
dp = [[0]*W for _ in range(H)]
memo = [[-1]*W for _ in range(H)]
mod = 10**9+7
result = 0
        
def aaa(x,y):
    move_list = [[x+1,y], [x-1, y], [x,y+1],[x,y-1]]
    val = A[x][y]
    cnt = 1

    for new_x, new_y in move_list:
        if 0 <= new_x <H and 0<=new_y<W and A[new_x][new_y] > val:
            cnt += aaa(new_x,new_y) if memo[new_x][new_y] == -1 else memo[new_x][new_y]
            cnt %= mod
    memo[x][y] = cnt
    return cnt


for i in range(H):
    for j in range(W):
        result += aaa(i,j)
print(result)

Submission status: Runtime Error

Solution code:
N, K, L = [int(x) for x in input().split()]
dict = {}
for i in range(1, N + 1):
    dict[i] = [set(), set()]
    dict[i][0].add(i)
    dict[i][1].add(i)
for i in range(K):
    p, q = [int(x) for x in input().split()]
    dict[p][0].add(q)
    dict[q][0].add(p)
for i in range(L):
    r, s = [int(x) for x in input().split()]
    dict[r][1].add(s)
    dict[s][1].add(r)

def my_dfs(city, opt, s):
    if dict[city][opt] <= s:
        return s
    for i in dict[city][opt]:
        if i in s:
            continue
        if i == city:
            s.add(i)
            continue
        s.add(i)
        s.update(my_dfs(i, opt, s))
    return s

for i in range(1, N + 1):
    dict[i][0].update(my_dfs(i, 0, set()))
    dict[i][1].update(my_dfs(i, 1, set()))
ans_lst = []
for i in range(1, N + 1):
    ans_lst.append(len(dict[i][0] & dict[i][1]))
print(*ans_lst)

Submission status: Runtime Error

Solution code:
N, K, L = [int(x) for x in input().split()]
dict = {}
for i in range(1, N + 1):
    dict[i] = [set(), set()]
    dict[i][0].add(i)
    dict[i][1].add(i)
for i in range(K):
    p, q = [int(x) for x in input().split()]
    dict[p][0].add(q)
    dict[q][0].add(p)
for i in range(L):
    r, s = [int(x) for x in input().split()]
    dict[r][1].add(s)
    dict[s][1].add(r)

def my_dfs(city, opt, s):
    if dict[city][opt] <= s:
        return s
    for i in dict[city][opt]:
        if i in s:
            continue
        if i == city:
            s.add(i)
            continue
        s.add(i)
        s.update(my_dfs(i, opt, s))
    return s

for i in range(1, N + 1):
    dict[i][0].update(my_dfs(i, 0, set()))
    dict[i][1].update(my_dfs(i, 1, set()))
ans_lst = []
for i in range(1, N + 1):
    ans_lst.append(len(dict[i][0] & dict[i][1]))
print(ans_lst)

Submission status: Runtime Error

Solution code:
import sys


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

    def finds(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.finds())

    def all_group_members(self):
        return {r: self.members(r) for r in self.finds()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.finds())


input = sys.stdin.readline
n, k, l = map(int, input().split())
w = [list(map(int, input().split())) for i in range(k+l)]

ro = w[:k]
ra = w[l:]
answer = ""
d = defaultdict(int)

ro_cl = UnionFind(n)
ra_cl = UnionFind(n)

for p, q in ro:
    ro_cl.union(p-1, q-1)

for p, q in ra:
    ra_cl.union(p-1, q-1)

for i in range(n):
    print(ro_cl.members(i))
    print(ra_cl.members(i))
    if i != 0:
        answer += " "
    answer += str(len([n for n in ro_cl.members(i) if n in ra_cl.members(i)]))
    # d[(ro_cl.find(i), ra_cl.find(i))] += 1

print(answer)

Submission status: Runtime Error

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]

p = UnionFind(n)
r = UnionFind(n)
ans = []
n, k, l = list(map(int,input().split()))
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)))