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:
# -*- coding: utf-8 -*-
import fractions
import sys
input = sys.stdin.readline


def main():
    n, k, l = map(int, input().split())
    p, q = [], []
    for _ in range(k):
        pi, qi = map(int, input().split())
        p.append(pi)
        q.append(qi)
    r, s = [], []
    for _ in range(l):
        ri, si = map(int, input().split())
        r.append(ri)
        s.append(si)

    road_tree = make_union_find(p, q, n)
    rail_tree = make_union_find(r, s, n)

    a = []
    for i in range(n):
        a.append(root(road_tree, i))
    b = []
    for i in range(n):
        b.append(root(rail_tree, i))

    x = {}
    for i in range(n):
        key = (a[i], b[i])
        if key in x:
            x[key].append(i)
        else:
            x[key] = [i]

    result = [0] * n
    for i in x.values():
        if len(i) > 1:
            for j in i:
                result[j] = 2
        else:
            for j in i:
                result[j] = 1

    print(*result)


def make_union_find(a, b, n):
    x = [i for i in range(n)]

    for i in range(len(a)):
        root = a[i] - 1
        leaf = b[i] - 1
        x[leaf] = root
    return x


def root(union_find_tree, target):
    if union_find_tree[target] == target:
        return target
    else:
        union_find_tree[target] = root(
            union_find_tree, union_find_tree[target])
        return union_find_tree[target]


def same(union_find_tree, x, y):
    return root(union_find_tree, x) == root(union_find_tree, y)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import fractions
import sys
input = sys.stdin.readline


def main():
    n, k, l = map(int, input().split())
    p, q = [], []
    for _ in range(k):
        pi, qi = map(int, input().split())
        p.append(pi)
        q.append(qi)
    r, s = [], []
    for _ in range(l):
        ri, si = map(int, input().split())
        r.append(ri)
        s.append(si)

    road_tree = make_union_find(p, q, n)
    rail_tree = make_union_find(r, s, n)

    a = []
    for i in range(n):
        a.append(root(road_tree, i))
    b = []
    for i in range(n):
        b.append(root(rail_tree, i))

    x = {}
    for i in range(n):
        key = (a[i], b[i])
        if key in x:
            x[key].append(i)
        else:
            x[key] = [i]

    result = [0] * n
    for i in x.values():
        if len(i) > 1:
            for j in i:
                result[j] = 2
        else:
            for j in i:
                result[j] = 1

    print(result)


def make_union_find(a, b, n):
    x = [i for i in range(n)]

    for i in range(len(a)):
        root = a[i] - 1
        leaf = b[i] - 1
        x[leaf] = root
    return x


def root(union_find_tree, target):
    if union_find_tree[target] == target:
        return target
    else:
        union_find_tree[target] = root(
            union_find_tree, union_find_tree[target])
        return union_find_tree[target]


def same(union_find_tree, x, y):
    return root(union_find_tree, x) == root(union_find_tree, y)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def resolve():
    N,K,L = map(int,input().split())
    root_k = list(range(N))
    root_l = list(range(N))
    depth_k = [1 for _ in range(N)]
    depth_l = [1 for _ in range(N)]
    def find(n,root,depth):
        if root[n] == n:
            return n
        else:
            root[n] = find(root[n],root,depth)
            return root[n]

    def unite(a,b,root,depth):
        A = find(a,root,depth)
        B = find(b,root,depth)
        if A == B:
            return
        else:
            if depth[A] > depth[B]:
                root[B] = A
                depth[A] += depth[B]
            else:
                root[A] = B
                depth[B] += depth[A]

    def same(a,b,root,depth):
        return find(a,root,depth) == find(b,root,depth)

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

    for _ in range(L):
        r,s = map(int,input().split())
        if same(r-1,s-1,root_k,depth_k):
            unite(r-1,s-1,root_l,depth_l)
    ans = [min(depth_k[find(i,root_k,depth_k)],depth_l[find(i,root_l,depth_l)]) for i in range(N)]
    print(*ans)
resolve()

Submission status: Wrong Answer

Solution code:
def resolve():
    N,K,L = map(int,input().split())
    root_k = list(range(N))
    root_l = list(range(N))
    depth_k = [1 for _ in range(N)]
    depth_l = [1 for _ in range(N)]
    def find(n,root,depth):
        if root[n] == n:
            return n
        else:
            root[n] = find(root[n],root,depth)
            return root[n]

    def unite(a,b,root,depth):
        A = find(a,root,depth)
        B = find(b,root,depth)
        if A == B:
            return
        else:
            if depth[A] > depth[B]:
                root[B] = A
                depth[A] += depth[B]
            else:
                root[A] = B
                depth[B] += depth[A]

    def same(a,b,root,depth):
        return find(a,root,depth) == find(b,root,depth)

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

    for _ in range(L):
        r,s = map(int,input().split())
        if same(r-1,s-1,root_k,depth_k):
            unite(r-1,s-1,root_l,depth_l)
    ans = [depth_l[find(i,root_l,depth_l)] for i in range(N)]
    print(*ans)
resolve()

Submission status: Wrong Answer

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

class UnionFind():
  def __init__(self,N):
    self.parents=list(range(N))
    self.size=[1]*N
  def find(self,x):
    if self.parents[x]==x:
      return x
    else:
      self.parents[x]=self.find(self.parents[x])
      return self.parents[x]
  def union(self,x,y):
    x,y=self.find(x),self.find(y)
    if x==y:
      return 
    if self.size[x]<self.size[y]:
      self.size[y]+=self.size[x]
      self.parents[x]=y
    else:
      self.size[x]+=self.size[y]
      self.parents[y]=x
      
ans=['1']*N
UF=UnionFind(N)
for i in range(K):
  x,y=map(int,input().split())
  UF.union(x-1,y-1)
for j in range(L):
  x,y=map(int,input().split())
  if UF.find(x-1)==UF.find(y-1):
    ans[x-1]=str(int(ans[x-1])+1)
    ans[y-1]=str(int(ans[y-1])+1)
      
print(' '.join(ans))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

class UnionFind:
    """ Union-Find木 """

    def __init__(self, n):
        self.n = n
        # 親要素のノード番号を格納。par[x] == xの時そのノードは根
        # 1-indexedのままでOK、その場合は[0]は未使用
        self.par = [i for i in range(n+1)]
        # 木の高さを格納する（初期状態では0）
        self.rank = [0] * (n+1)
        # あるノードを根とする集合に属するノード数
        self.size = [1] * (n+1)
        # あるノードを根とする集合が木かどうか
        self.tree = [True] * (n+1)

    def find(self, 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 = self.find(x)
        y = self.find(y)

        # 木かどうかの判定用
        if x == y:
            self.tree[x] = False
            return
        if not self.tree[x] or not self.tree[y]:
            self.tree[x] = self.tree[y] = False

        # 木の高さを比較し、低いほうから高いほうに辺を張る
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            # 木の高さが同じなら片方を1増やす
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def same(self, x, y):
        """ 同じ集合に属するか判定 """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """ あるノードの属する集合のノード数 """
        return self.size[self.find(x)]
    
    def is_tree(self, x):
        """ 木かどうかの判定 """
        return self.tree[self.find(x)]

    def len(self):
        """ 集合の数 """
        res = set()
        for i in range(self.n+1):
            res.add(self.find(i))
        # グループ0の分を引いて返却
        return len(res) - 1

N, K, L = MAP()
uf = UnionFind(N)
uf2 = UnionFind(N)

for i in range(K):
    a, b = MAP()
    uf.union(a, b)

for i in range(L):
    a, b = MAP()
    if uf.same(a, b):
        uf2.union(a, b)

ans = [0] * N
for i in range(N):
    ans[i] = uf2.get_size(i+1)
print(*ans)

Submission status: Wrong Answer

Solution code:
class UF:
    def __init__(self, N):
        self.uf = [-1]*N

    def find(self, x):
        if self.uf[x]<0: return x
        self.uf[x] = self.find(self.uf[x])
        return self.uf[x]

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

    def union(self, x, y):
        x, y = self.find(x), self.find(y)
        if x==y: return
        if self.size(x) > self.size(y): x, y = y, x
        self.uf[y] += self.uf[x]
        self.uf[x] = y

N, K, L = list(map(int, input().split()))
uf1, uf2 = UF(N), UF(N)
for _ in range(K):
    p, q = list(map(int, input().split()))
    uf1.union(p-1, q-1)

for _ in range(L):
    r, s = list(map(int, input().split()))
    if uf1.find(r-1)==uf1.find(s-1):
        uf2.union(r-1, s-1)

print(*[uf2.size(x) for x in range(N)])

Submission status: Wrong Answer

Solution code:

def wantp(lis,n):

    q = []
    while lis[n] != n:
        q.append(n)
        n = lis[n]

    for i in q:
        lis[i] = n

    return n


N,K,L = map(int,input().split())
rp = [i for i in range(N)]
rank = [1 for i in range(N)]
pqlis = []

for i in range(K):

    P,Q = map(int,input().split())
    P -= 1
    Q -= 1

    PP = wantp(rp,P)
    QP = wantp(rp,Q)
    pqlis.append([P,Q])

    if PP != QP:

        if rank[PP] < rank[QP]:
            rp[PP] = QP

        elif rank[QP] < rank[PP]:
            rp[QP] = PP

        else:
            rp[QP] = PP
            rank[QP] += 1

#print (rp)

tp = [i for i in range(N)]
rank = [1 for i in range(N)]


for i in range(L):

    P,Q = map(int,input().split())
    P-=1
    Q-=1
    pqlis.append([P,Q])

    PP = wantp(tp,P)
    QP = wantp(tp,Q)

    #print (PP,QP,PP2,PQ2)

    if PP != QP:

        if rank[PP] < rank[QP]:
            tp[PP] = QP

        elif rank[QP] < rank[PP]:
            tp[QP] = PP

        else:
            tp[QP] = PP
            rank[QP] += 1

sp = [i for i in range(N)]
rank = [1 for i in range(N)]
for i in range(L+K):

    P = pqlis[i][0]
    Q = pqlis[i][1]

    PP = wantp(sp,P)
    QP = wantp(sp,Q)
    P2 = wantp(rp,P)
    Q2 = wantp(rp,Q)
    P3 = wantp(tp,P)
    Q3 = wantp(tp,Q)

    #print (PP,QP,PP2,PQ2)

    if PP != QP and P2 == Q2 and P3 == Q3:

        if rank[PP] < rank[QP]:
            sp[PP] = QP

        elif rank[QP] < rank[PP]:
            sp[QP] = PP

        else:
            sp[QP] = PP
            rank[QP] += 1


#print (tp)
dic = {}

for i in range(N):
    tpp = wantp(sp,i)
    if tpp not in dic:
        dic[tpp] = 1
    else:
        dic[tpp] += 1

#print (dic)
ans = []
for i in range(N):
    tpp = wantp(sp,i)
    ans.append(dic[tpp])

print (" ".join(map(str,ans)))

Submission status: Wrong Answer

Solution code:

def wantp(lis,n):

    q = []
    while lis[n] != n:
        q.append(n)
        n = lis[n]

    for i in q:
        lis[i] = n

    return n


N,K,L = map(int,input().split())
rp = [i for i in range(N)]
rank = [1 for i in range(N)]

for i in range(K):

    P,Q = map(int,input().split())
    P -= 1
    Q -= 1

    PP = wantp(rp,P)
    QP = wantp(rp,Q)

    if PP != QP:

        if rank[PP] < rank[QP]:
            rp[PP] = QP

        elif rank[QP] < rank[PP]:
            rp[QP] = PP

        else:
            rp[QP] = PP
            rank[QP] += 1

#print (rp)

tp = [i for i in range(N)]
rank = [1 for i in range(N)]

for i in range(L):

    P,Q = map(int,input().split())
    P-=1
    Q-=1

    PP = wantp(tp,P)
    QP = wantp(tp,Q)


    PP2 = wantp(rp,P)
    PQ2 = wantp(rp,Q)

    #print (PP,QP,PP2,PQ2)

    if PP != QP and PP2 == PQ2:

        if rank[PP] < rank[QP]:
            tp[PP] = QP

        elif rank[QP] < rank[PP]:
            tp[QP] = PP

        else:
            tp[QP] = PP
            rank[QP] += 1

    #print (tp)

#print (tp)
dic = {}

for i in range(N):
    tpp = wantp(tp,i)
    if tpp not in dic:
        dic[tpp] = 1
    else:
        dic[tpp] += 1

#print (dic)
ans = []
for i in range(N):
    tpp = wantp(tp,i)
    ans.append(dic[tpp])

print (" ".join(map(str,ans)))

Submission status: Wrong Answer

Solution code:

def wantp(lis,n):

    q = []
    while lis[n] != n:
        q.append(n)
        n = lis[n]

    for i in q:
        lis[i] = n

    return n


N,K,L = map(int,input().split())
rp = [i for i in range(N)]
rank = [1 for i in range(N)]

for i in range(K):

    P,Q = map(int,input().split())
    P -= 1
    Q -= 1

    PP = wantp(rp,P)
    QP = wantp(rp,Q)

    if PP != QP:

        if rank[PP] < rank[QP]:
            rp[PP] = QP

        elif rank[QP] < rank[PP]:
            rp[QP] = PP

        else:
            rp[QP] = PP
            rank[QP] += 1

#print (rp)

tp = [i for i in range(N)]
rank = [1 for i in range(N)]

for i in range(L):

    P,Q = map(int,input().split())
    P-=1
    Q-=1

    PP = wantp(tp,P)
    QP = wantp(tp,Q)


    PP2 = wantp(rp,P)
    PQ2 = wantp(rp,Q)

    #print (PP,QP,PP2,PQ2)

    if PP != QP and PP2 == PQ2:

        if rank[PP] < rank[QP]:
            tp[PP] = QP

        elif rank[QP] < rank[PP]:
            tp[QP] = PP

        else:
            tp[QP] = PP
            rank[QP] += 1

    #print (tp)

#print (tp)
dic = {}

for i in range(N):
    tpp = wantp(tp,i)
    if tpp not in dic:
        dic[tpp] = 1
    else:
        dic[tpp] += 1

#print (dic)
for i in range(N):
    tpp = wantp(tp,i)
    print (dic[tpp])

Submission status: Wrong Answer

Solution code:

def wantp(lis,n):

    q = []
    if lis[n] != n:
        q.append(n)
        n = lis[n]

    for i in q:
        lis[i] = n

    return n


N,K,L = map(int,input().split())
rp = [i for i in range(N)]
rank = [1 for i in range(N)]

for i in range(K):

    P,Q = map(int,input().split())
    P -= 1
    Q -= 1

    PP = wantp(rp,P)
    QP = wantp(rp,Q)

    if PP != QP:

        if rank[PP] < rank[QP]:
            rp[PP] = QP

        elif rank[QP] < rank[PP]:
            rp[QP] = PP

        else:
            rp[QP] = PP
            rank[QP] += 1


tp = [i for i in range(N)]
rank = [1 for i in range(N)]

for i in range(L):

    P,Q = map(int,input().split())
    P-=1
    Q-=1

    PP = wantp(tp,P)
    QP = wantp(tp,Q)

    PP2 = wantp(rp,P)
    PQ2 = wantp(rp,Q)

    if PP != QP and PP2 == PQ2:

        if rank[PP] < rank[QP]:
            tp[PP] = QP

        elif rank[QP] < rank[PP]:
            tp[QP] = PP

        else:
            tp[QP] = PP
            rank[QP] += 1


dic = {}

for i in range(N):
    if tp[i] not in dic:
        dic[tp[i]] = 1
    else:
        dic[tp[i]] += 1

#print (dic)
for i in range(N):
    print (dic[tp[i]])

Submission status: Wrong Answer

Solution code:
import collections
N, K, L = [int(x) for x in input().split(' ')]
railway = list(range(N))
road = list(range(N))

def find(f, x):
    if x != f[x]:
        f[x] = find(f, f[x])
    return f[x]

def union(f, x, y):
    f[find(f, x)] = find(f, y)
rail_cnt = collections.defaultdict(set)
road_cnt = collections.defaultdict(set)
for _ in range(K):
    a, b = [int(x)-1 for x in input().split(' ')]
    union(railway, a, b)
for i in range(N):
    rail_cnt[find(railway, i)].add(i)
print(rail_cnt)
for _ in range(L):
    a, b = [int(x)-1 for x in input().split(' ')]
    union(road, a, b)
for i in range(N):
    road_cnt[find(road, i)].add(i)
res = []
for i in range(N):
    cur = road_cnt[find(road, i)] & rail_cnt[find(railway, i)]
    res.append(str(len(cur)))
print(' '.join(res))

Submission status: Wrong Answer

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.root = [-1] * (n + 1)
        self.rnk = [0] * (n + 1)

    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):
        x = self.find_root(x)
        y = self.find_root(y)
        if x == y:
            return
        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
            if self.rnk[x] == self.rnk[y]:
                self.rnk[y] += 1

    def isSameGroup(self, x, y):
        return self.find_root(x) == self.find_root(y)

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


N, K, L = map(int, input().split())
UFc = UnionFind(N)
UFt = UnionFind(N)
UFall = UnionFind(N)
car = []
train = []
for _ in range(K):
    p, q = map(int, input().split())
    car.append((p, q))
    UFc.unite(p, q)
for _ in range(L):
    p, q = map(int, input().split())
    train.append((p, q))
    UFt.unite(p, q)
for i in range(K):
    p, q = car[i]
    if UFt.isSameGroup(p, q):
        UFall.unite(p, q)
for i in range(L):
    p, q = train[i]
    if UFc.isSameGroup(p, q):
        UFall.unite(p, q)

ans = [0] * N
for i in range(N):
    ans[i] = UFall.size(i + 1)
print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import Counter, deque, defaultdict
from math import factorial
import heapq, bisect
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10*5
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))

class UnionFind():

    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.rnk = [0]*(n+1)

    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):
        x = self.Find_Root(x)
        y = self.Find_Root(y)

        if(x == y):
            return 

        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
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1


    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    def Count(self, x):
        return -self.root[self.Find_Root(x)]

n, k, l = MAP()
road = [0]*k
train = [0]*l
for i in range(k):
    p, q = MAP()
    road[i] = (p,q)
for i in range(l):
    r, s = MAP()
    train[i] = (r,s)

ans = [1]*n

uf = UnionFind(n)

for i in range(k):
    uf.Unite(road[i][0]-1, road[i][1]-1)
for i in range(l):
    if uf.isSameGroup(train[i][0]-1, train[i][1]-1):
        ans[train[i][0]-1] += 1
        ans[train[i][1]-1] += 1
    
for i in range(n):
    print(str(ans[i]) + " ", end = "")

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
par = list(range(N+1))
rank = [0] * (N+1)
cnt = [1] * (N+1)
def root(x):
  if par[x] == x:
    return x
  else:
    par[x] = root(par[x])
    return par[x]

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

def unite(x, y):
  xr = root(x)
  yr = root(y)
  if xr == yr:
    return
  if rank[xr] < rank[yr]:
    par[xr] = yr
  else:
    par[yr] = xr
    if rank[xr] == rank[yr]:
      rank[xr] += 1

for _ in range(K):
  x, y = map(int, input().split())
  unite(x, y)
par_r = par[:]
par = list(range(N+1))
for _ in range(L):
  x, y = map(int, input().split())
  unite(x, y)
ans = [1] * (N)
r_dict = {}

for i in range(1, N+1):
  if (par_r[i], par[i]) in r_dict:
    r_dict[(par_r[i], par[i])] += 1
  else:
    r_dict[(par_r[i], par[i])] = 1
ans = []
for i in range(1, N+1):
  ans.append(r_dict[(par_r[i], par[i])])
print(' '.join(map(str, ans)))

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
par = list(range(N+1))
rank = [0] * (N+1)
cnt = [1] * (N+1)
def root(x):
  if par[x] == x:
    return x
  else:
    par[x] = root(par[x])
    return par[x]

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

def unite(x, y):
  xr = root(x)
  yr = root(y)
  if xr == yr:
    return
  if rank[xr] < rank[yr]:
    par[xr] = par[yr]
  else:
    par[yr] = par[xr]
    if rank[xr] == rank[yr]:
      rank[xr] += 1

for _ in range(K):
  x, y = map(int, input().split())
  unite(x, y)
par_r = par[:]
par = list(range(N+1))
for _ in range(L):
  x, y = map(int, input().split())
  unite(x, y)
ans = [1] * (N)
r_dict = {}

for i in range(1, N+1):
  if (par_r[i], par[i]) in r_dict:
    r_dict[(par_r[i], par[i])] += 1
  else:
    r_dict[(par_r[i], par[i])] = 1
ans = []
for i in range(1, N+1):
  ans.append(r_dict[(par_r[i], par[i])])
print(' '.join(map(str, ans)))

Submission status: Wrong Answer

Solution code:

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




class Union_Find():
	def __init__(self, n):
		self.union = [i for i in range(n)]
		self.level = [0 for i in range(n)]
		self.group = [[i] for i in range(n)]

	def root(self, i, mode=0):
		keiro = [i]
		ans = i
		while ans != self.union[ans]:
			ans = self.union[ans]
			keiro.append(ans)
		if mode == 0:
			return ans
		else:
			return ans, keiro

	def unite(self, i, j):
		root_i, list_i = self.root(i, 1)
		root_j, list_j = self.root(j, 1)
		if root_i != root_j:
			if self.level[root_i] < self.level[root_j]:
				self.group[root_j].extend(self.group[root_i])
				self.level[root_j] = max(self.level[root_i] + 1, self.level[root_j])
				for node in list_i:
					self.union[node] = root_j
			else:
				self.group[root_i].extend(self.group[root_j])
				self.level[root_i] = max(self.level[root_j] + 1, self.level[root_i])
				for node in list_j:
					self.union[node] = root_i

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

UF_road = Union_Find(N)
UF_train = Union_Find(N)
for i in range(K):
	p, q = list(map(int, input().split()))
	p -= 1
	q -= 1
	UF_road.unite(p,q)
for i in range(L):
	p, q = list(map(int, input().split()))
	p -= 1
	q -= 1
	UF_train.unite(p,q)
    
exit()

number = [-1 for i in range(N)]
for i in range(N):
	if number[i] == -1:
		if True:
			x = i
			road = UF_road.group[UF_road.root(x)]
			while len(road) > 0:
				train = set(UF_train.group[UF_train.root(road[0])])
				road = set(road)
				double = road & train
				road -= double
				double = list(double)
				num = len(double)
				for town in double:
					number[town] = num
				road = list(road)
		

def list_print(A):
	length = len(A)
	for i in range(length - 1):
		print(A[i], end="")
		print(" ", end="")
	print(A[N - 1])

list_print(number)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 11:26:39 2019
D - 連結 / Connectivity
実行時間制限: 2 sec / メモリ制限: 256 MB

配点 : 
400 点
@author: justwah
"""
from collections import Counter
import sys

input = sys.stdin.readline # use this runtime 1523 ms> 1214ms

class UnionFind:
    def __init__(self, N):
        self.rank = [0]*N
        self.parent = [i for i in range(N)]
        self.n = N
        
    def root(self, x):
        if self.parent[x] == x:
            return x
        else:
            self.parent[x] = self.root(self.parent[x])
            return self.parent[x]
        
    def merge(self, a, b):
        a = self.root(a)
        b = self.root(b)
        if a == b:
            return
        if self.rank[a] < self.rank[b]:
            self.parent[a] = b
        else:
            self.parent[b] = a
            if self.rank[a] == self.rank[b]:
                self.rank[a] +=1
                
    def same(self, a, b):
        return self.root(a) == self.roob(b)


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

uf_road = UnionFind(n)
for _ in range(k):
    p, q = map(int, input().split())
    uf_road.merge(p-1, q-1)

uf_rail = UnionFind(n)
for _ in range(l):
    r, s = map(int, input().split())
    uf_rail.merge(r-1, s-1)
    
ctr = Counter()
for i in range(n):  # make a list to count number of cities that both road and rail-wise are in the same group
    r1 = uf_road.root(i)
    r2 = uf_rail.root(i)
    ctr[(r1,r2)] += 1 # works like a dictionary, with unique index (the combinations)

ans = []
for i in range(n): # print the group size of that city when looped (retrival of dict)
    ans.append(ctr[(r1,r2)])

print(*ans)   # * is for unpack the list

Submission status: Wrong Answer

Solution code:

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
##############################

class UnionFind:
    def __init__(self, N):
        self.rank = [0] * N
        self.parent = [i for i in range(N)]
        self.n = N

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

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

        if (self.rank[x] < self.rank[y]):
            self.parent[x] = y
        else:
            self.parent[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

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


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)

trains = [ [0 for _ in range(N)] for _ in range(N) ]
for i in range(L):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    trains[r][s] = 1
    trains[s][r] = 1
    

ans = [0] * N
for y in range(N):
    for x in range(N):
        if trains[y][x] == 0:
            ans[y] = max(ans[y], 1)
            continue

        same = 2 if uf.same(y, x) else 1
        ans[y] = max(ans[y], same)


print(*ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.root = [-1]*(n+1)
    self.rnk = [0]*(n+1)

  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):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if(x == y):
      return 
    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
      if(self.rnk[x] == self.rnk[y]):
        self.rnk[y] += 1

  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
    
  def Count(self, x):
    return -self.root[self.Find_Root(x)]
N, K, L = map(int, input().split())
k = UnionFind(N)
l = UnionFind(N)
checkset = set()
res = [1] * (N + 1)
roots = dd(int)
for _ in range(K):
  x, y = map(int, input().split())
  k.Unite(x, y)
  checkset.add(x)
  checkset.add(y)
for _ in range(L):
  x, y = map(int, input().split())
  l.Unite(x, y)
  checkset.add(x)
  checkset.add(y)
for i in list(checkset):
  kr = k.Find_Root(i)
  lr = l.Find_Root(i)
  roots[(min(kr, lr), max(kr, lr))] += 1
#print(roots)
for i in list(checkset):
  kr = k.Find_Root(i)
  lr = l.Find_Root(i)
  res[i] = roots[(min(kr, lr), max(kr, lr))]
  
print(*(res[1: ]))

Submission status: Wrong Answer

Solution code:
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.root = [-1]*(n+1)
    self.rnk = [0]*(n+1)

  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):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if(x == y):
      return 
    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
      if(self.rnk[x] == self.rnk[y]):
        self.rnk[y] += 1

  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
    
  def Count(self, x):
    return -self.root[self.Find_Root(x)]
N, K, L = map(int, input().split())
k = UnionFind(N)
res = [1] * (N + 1)
for _ in range(K):
  x, y = map(int, input().split())
  k.Unite(x, y)
for _ in range(L):
  x, y = map(int, input().split())
  if k.isSameGroup(x, y):
    res[x] += 1
    res[y] += 1
print(*(res[1: ]))