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:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
    c=0
    s=[0]*n
    label=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            label[c-1]=c
            stack=deque([i])
            while stack:
                w=stack.pop()
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
                    elif s[wn-1]<c:
                        label[s[wn-1]-1]=c
    return [label[s[w]-1] for w in range(n)] 
           
def main(n,k,l,e1,e2):
    d1=components(n,k,e1)
    d2=components(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
    c=0
    s=[0]*n
    label=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            label[c-1]=c
            stack=deque([i])
            while stack:
                w=stack.pop()
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
                    elif s[wn-1]<c:
                        label[s[wn-1]-1]=c
    return [label[s[w]] for w in range(n)] 
           
def main(n,k,l,e1,e2):
    d1=components(n,k,e1)
    d2=components(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
    c=0
    s=[0]*n
    label=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            label[c]=c
            stack=deque([i])
            while stack:
                w=stack.pop()
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
                #    elif s[wn-1]<c:
                #        label[s[wn-1]]=c
    return [label[s[w]] for w in range(n)] 
           
def main(n,k,l,e1,e2):
    d1=components(n,k,e1)
    d2=components(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
    c=0
    s=[0]*n
    label=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            label[c]=c
            stack=deque([i])
            while stack:
                w=stack.pop() 
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
                    elif s[wn-1]<c:
                        label[s[wn-1]]=c
    return [label[s[w]] for w in range(n)] 
           
def main(n,k,l,e1,e2):
    d1=components(n,k,e1)
    d2=components(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    # print(d1,d2,d,p)
    d[(k,l)]=1
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
#Union Find
class union_find:
    #初期化
    #根なら-size,子なら親の頂点
    # par = [-1]*N
    def __init__(self, par):
        self.par = par

    #xの根を求める
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    #xとyの属する集合の併合
    def unite(self, x,y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return False
        else:
            #sizeの大きいほうがx
            if self.par[x] > self.par[y]:
                x,y = y,x
            self.par[x] += self.par[y]
            self.par[y] = x
            return True

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

    #xが属する集合の個数
    def size(self, x):
        return -self.par[self.find(x)]

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

par1 = [-1]*N
uf1 = union_find(par1)
for _ in range(K):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf1.unite(p, q)

par2 = [-1]*N
uf2 = union_find(par2)
for _ in range(L):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    uf2.unite(r, s)

for i in range(N):
    if par1[i] < 0: par1[i] = i
    if par2[i] < 0: par2[i] = i

par12 = [(p1, p2) for p1, p2 in zip(par1, par2)]
dic = {p12:0 for p12 in set(par12)}
for p12 in par12:
    dic[p12] += 1

ans = [0]*N
for i in range(N):
    ans[i] = dic[par12[i]]

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

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(-1,(-1)*n-1,-1)))
    td=defaultdict(lambda:deque([])) #tdは同値類がキーで中の元が値
    c=1
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a] #da,dbはa,bの含まれる同値流のラベル
        db=d[b]
        if da<0 and db<0:
            d[a]=c
            d[b]=c
            td[c].append(a)
            td[c].append(b)
            c+=1
        elif da>0 and db<0:
            d[b]=da
            td[d[a]].append(b)
        elif da<0 and db>0:
            d[a]=db
            td[d[b]].append(a)
        elif da>0 and db>0 and da!=db:
            for x in td[db]:
                d[x]=da
                td[da].append(x)

    return list(d.values())

def components(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
        ed[edge[1]].append(edge[0])
    print(ed)
    c=0
    s=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            stack=deque([i])
            while stack:
                w=stack.pop() 
                s[w-1]=c
                while ed[w]:
                    wn=ed[w].pop()
                    if s[wn-1]==0:
                        s[wn-1]=c
                        if ed[wn]:
                            stack.append(w)
                            w=wn
    return s
           
def main(n,k,l,e1,e2):
    d1=components(n,k,e1)
    d2=components(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    d=Counter(p)
    print(d1,d2,d,p)
    d[(k,l)]=1
    print(' '.join([str(d[x]) for x in p])) 

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
#Union Find
class union_find:
    #初期化
    #根なら-size,子なら親の頂点
    # par = [-1]*N
    def __init__(self, par):
        self.par = par

    #xの根を求める
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    #xとyの属する集合の併合
    def unite(self, x,y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return False
        else:
            #sizeの大きいほうがx
            if self.par[x] > self.par[y]:
                x,y = y,x
            self.par[x] += self.par[y]
            self.par[y] = x
            return True

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

    #xが属する集合の個数
    def size(self, x):
        return -self.par[self.find(x)]

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

par1 = [-1]*N
uf1 = union_find(par1)
for _ in range(K):
    p, q = map(int, input().split())
    p -= 1
    q -= 1
    uf1.unite(p, q)

par2 = [-1]*N
uf2 = union_find(par2)
for _ in range(L):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    if uf1.same(r, s):
        uf2.unite(r, s)

ans = [0]*N
for i in range(N):
    ans[i] = uf2.size(i)

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

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(1,n+1)))
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a]
        db=d[b]
        d[a]=min(da,db)
        d[b]=min(da,db)
    return d.values()

def main(n,k,l,e1,e2):
    d1=conn(n,k,e1)
    d2=conn(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    # print(p)
    d=Counter(p)
    # print(d)
    d[(k,l)]=1
    print(' '.join([str(d[x]) for x in p]))

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(1,n+1)))
    c=0
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a]
        db=d[b]
        if da==m and db==m:
            d[a]=c
            d[b]=c
            c+=1
        else:
            d[a]=min(da,db)
            d[b]=min(da,db)
    return d.values()

def main(n,k,l,e1,e2):
    d1=conn(n,k,e1)
    d2=conn(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    # print(p)
    d=Counter(p)
    # print(d)
    d[(k,l)]=1
    print(' '.join([str(d[x]) for x in p]))

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
from collections import Counter

def conn(n,m,e):
    d=dict(zip(range(1,n+1),range(1,n+1)))
    c=0
    for edge in e:
        a=edge[0]
        b=edge[1]
        da=d[a]
        db=d[b]
        if da==m and db==m:
            d[a]=c
            d[b]=c
            c+=1
        else:
            d[a]=min(da,db)
            d[b]=min(da,db)
    return d.values()

def main(n,k,l,e1,e2):
    d1=conn(n,k,e1)
    d2=conn(n,l,e2)
    p=tuple(zip(iter(d1),iter(d2)))
    print(p)
    d=Counter(p)
    print(d)
    d[(k,l)]=1
    print(' '.join([str(d[x]) for x in p]))

if __name__=='__main__':
    ssr=sys.stdin.readline
    n,k,l=map(int,ssr().strip().split())
    e1=[]
    e2=[]
    for _ in range(k):
        e1.append(tuple(map(int,ssr().strip().split())))
    for _ in range(l):
        e2.append(tuple(map(int,ssr().strip().split())))
    main(n,k,l,e1,e2)

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

# 木の根を求める
def root(x):
    if par[x] == x:             # 根の時
        return x
    else:
        par[x] = root(par[x])   # 経路圧縮
        return par[x]

# xとyの属する集合を併合(ランク有)
def unite(x,y):
    x = root(x)
    y = root(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y              # xの親をyに
        size[y] += size[x]      # yの頂点数+=xの頂点数
    else:
        par[y] = x              # yの親をxに
        size[x] += size[y]      # xの頂点数+=yの頂点数
        if rank[x] == rank[y]:
            rank[x] += 1

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

road = [tuple(map(int,readline().split())) for i in range(K)]
train = [tuple(map(int,readline().split())) for i in range(L)]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in road:
    unite(a,b)
for i in range(1,N+1):
    par[i] = root(i)

parroad = par[::]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    unite(a,b)
for i in range(1,N+1):
    par[i] = root(i)

partrain = par[::]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    if parroad[root(a)] == parroad[root(b)]:
        unite(a,b)

for (a,b) in road:
    if partrain[root(a)] == partrain[root(b)]:
        unite(a,b)

for i in range(1,N+1):
    if i != N:
        print(size[root(i)],end=" ")
    else:
        print(size[root(i)])

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

# 木の根を求める
def root(x):
    if par[x] == x:             # 根の時
        return x
    else:
        par[x] = root(par[x])   # 経路圧縮
        return par[x]

# xとyの属する集合を併合(ランク有)
def unite(x,y):
    x = root(x)
    y = root(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y              # xの親をyに
        size[y] += size[x]      # yの頂点数+=xの頂点数
    else:
        par[y] = x              # yの親をxに
        size[x] += size[y]      # xの頂点数+=yの頂点数
        if rank[x] == rank[y]:
            rank[x] += 1

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

road = [tuple(map(int,readline().split())) for i in range(K)]
train = [tuple(map(int,readline().split())) for i in range(L)]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in road:
    unite(a,b)
for i in range(N+1):
    par[i] = root(i)

parroad = par[::]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    unite(a,b)
for i in range(N+1):
    par[i] = root(i)

partrain = par[::]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    if parroad[a] == parroad[b]:
        unite(a,b)

for (a,b) in road:
    if partrain[a] == partrain[b]:
        unite(a,b)

for i in range(1,N+1):
    if i != N:
        print(size[root(i)],end=" ")
    else:
        print(size[root(i)])

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

# 木の根を求める
def root(x):
    if par[x] == x:             # 根の時
        return x
    else:
        par[x] = root(par[x])   # 経路圧縮
        return par[x]

# xとyの属する集合を併合(ランク有)
def unite(x,y):
    x = root(x)
    y = root(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y              # xの親をyに
        size[y] += size[x]      # yの頂点数+=xの頂点数
    else:
        par[y] = x              # yの親をxに
        size[x] += size[y]      # xの頂点数+=yの頂点数
        if rank[x] == rank[y]:
            rank[x] += 1

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

road = [tuple(map(int,readline().split())) for i in range(K)]
train = [tuple(map(int,readline().split())) for i in range(L)]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in road:
    unite(a,b)

parroad = par[::]

for i in range(N+1):
    parroad[i] = root(i)

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    unite(a,b)

partrain = par[::]

for i in range(N+1):
    partrain[i] = root(i)

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    if parroad[a] == parroad[b]:
        unite(a,b)

for (a,b) in road:
    if partrain[a] == partrain[b]:
        unite(a,b)

for i in range(1,N+1):
    if i != N:
        print(size[par[i]],end=" ")
    else:
        print(size[par[i]])

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

# 木の根を求める
def root(x):
    if par[x] == x:             # 根の時
        return x
    else:
        par[x] = root(par[x])   # 経路圧縮
        return par[x]

# xとyの属する集合を併合(ランク有)
def unite(x,y):
    x = root(x)
    y = root(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y              # xの親をyに
        size[y] += size[x]      # yの頂点数+=xの頂点数
    else:
        par[y] = x              # yの親をxに
        size[x] += size[y]      # xの頂点数+=yの頂点数
        if rank[x] == rank[y]:
            rank[x] += 1

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

road = [tuple(map(int,readline().split())) for i in range(K)]
train = [tuple(map(int,readline().split())) for i in range(L)]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in road:
    unite(a,b)

parroad = par[::]

for i in range(N+1):
    parroad[i] = root(i)

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    unite(a,b)

partrain = par[::]

for i in range(N+1):
    partrain[i] = root(i)

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)


for (a,b) in road:
    if partrain[a] == partrain[b]:
        unite(a,b)

for i in range(1,N+1):
    if i != N:
        print(size[root(i)],end=" ")
    else:
        print(size[root(i)])

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

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

road = [tuple(map(int,readline().split())) for i in range(K)]
train = [tuple(map(int,readline().split())) for i in range(L)]

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

# 木の根を求める
def root(x):
    if par[x] == x:             # 根の時
        return x
    else:
        par[x] = root(par[x])   # 経路圧縮
        return par[x]

# xとyの属する集合を併合(ランク有)
def unite(x,y):
    x = root(x)
    y = root(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y              # xの親をyに
        size[y] += size[x]      # yの頂点数+=xの頂点数
    else:
        par[y] = x              # yの親をxに
        size[x] += size[y]      # xの頂点数+=yの頂点数
        if rank[x] == rank[y]:
            rank[x] += 1
 
for (a,b) in road:
    unite(a,b)

parroad = par[::]

for i in range(N+1):
    parroad[i] = root(i)

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    unite(a,b)

partrain = par[::]

for i in range(N+1):
    partrain[i] = root(i)

par = [i for i in range(N+1)]
rank = [0]*(N+1)
size = [1]*(N+1)

for (a,b) in train:
    if parroad[a] == parroad[b]:
        unite(a,b)

for (a,b) in road:
    if partrain[a] == partrain[b]:
        unite(a,b)

for i in range(1,N+1):
    if i != N:
        print(size[root(i)],end=" ")
    else:
        print(size[root(i)])

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

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

# 1-indexed union-find
# parent(親)
par = [i for i in range(N+1)]
# rank(深さ)
rank = [0]*(N+1)
# 同グループの頂点数
size = [1]*(N+1)

# 木の根を求める
def root(x):
    if par[x] == x:             # 根の時
        return x
    else:
        par[x] = root(par[x])   # 経路圧縮
        return par[x]

# xとyの属する集合を併合(ランク有)
def unite(x,y):
    x = root(x)
    y = root(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y              # xの親をyに
        size[y] += size[x]      # yの頂点数+=xの頂点数
    else:
        par[y] = x              # yの親をxに
        size[x] += size[y]      # xの頂点数+=yの頂点数
        if rank[x] == rank[y]:
            rank[x] += 1
 
for i in range(K):
    a,b = map(int,input().split())
    unite(a,b)

parroad = par[::]

for i in range(N+1):
    parroad[i] = root(i)

# 1-indexed union-find
# parent(親)
par = [i for i in range(N+1)]
# rank(深さ)
rank = [0]*(N+1)
# 同グループの頂点数
size = [1]*(N+1)

for i in range(L):
    a,b = map(int,readline().split())
    if parroad[a] == parroad[b]:
        unite(a,b)

for i in range(1,N+1):
    if i != N:
        print(size[root(i)],end=" ")
    else:
        print(size[root(i)])

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

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

# 1-indexed union-find
# parent(親)
par = [i for i in range(N+1)]
# rank(深さ)
rank = [0]*(N+1)
# 同グループの頂点数
size = [1]*(N+1)

# 木の根を求める
def root(x):
    if par[x] == x:             # 根の時
        return x
    else:
        par[x] = root(par[x])   # 経路圧縮
        return par[x]

# xとyの属する集合を併合(ランク有)
def unite(x,y):
    x = root(x)
    y = root(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y              # xの親をyに
        size[y] += size[x]      # yの頂点数+=xの頂点数
    else:
        par[y] = x              # yの親をxに
        size[x] += size[y]      # xの頂点数+=yの頂点数
        if rank[x] == rank[y]:
            rank[x] += 1
 
for i in range(K):
    a,b = map(int,input().split())
    unite(a,b)

parroad = par[::]

for i in range(N+1):
    parroad[i] = root(i)

# 1-indexed union-find
# parent(親)
par = [i for i in range(N+1)]
# rank(深さ)
rank = [0]*(N+1)
# 同グループの頂点数
size = [1]*(N+1)

for i in range(L):
    a,b = map(int,readline().split())
    if parroad[a] == parroad[b]:
        unite(a,b)

for i in range(1,N+1):
    print(size[root(i)],end=" ")
print()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
class unionfind:#早いunionfind,class[i]のように要素指定すると親を得ることができる
    def __init__(self, elements=None):#elementsで初期化
        if elements is None:
            elements = ()
        self.parents = {}
        self.weights = {}
        for x in elements:
            self.weights[x] = 1
            self.parents[x] = x

    def __getitem__(self, i):
        # check for previously unknown i
        if i not in self.parents:
            self.parents[i] = i
            self.weights[i] = 1
            return i
        path = [i]
        root = self.parents[i]
        while root != path[-1]:
            path.append(root)
            root = self.parents[root]
        for ancestor in path:#縮約
            self.parents[ancestor] = root
        return root

    def __iter__(self):#for parent in Class:
        return iter(self.parents)

    def union(self, *objects):#オブジェクトをすべて結合
        roots = [self[x] for x in objects]
        heaviest = max(roots, key=lambda r: self.weights[r])
        for r in roots:
            if r != heaviest:
                self.weights[heaviest] += self.weights[r]
                self.parents[r] = heaviest

    def __len__(self):
        return len(self.parents)

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, K, L = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    train=unionfind(range(N))
    rail=unionfind(range(N))
    for i in range(K):#木の場合M=N-1
        a,b = map(int,input().split())
        train.union(a-1,b-1)

    for i in range(L):#木の場合M=N-1
        a,b = map(int,input().split())
        a-=1
        b-=1
        if train[a]==train[b]:
            rail.union(a,b)
    ans=[0]*N
    c=Counter()
    for i in range(N):
        c[rail[i]]+=1

    for i in range(N):
        ans[i]=c[rail[i]]
    print(*ans)
        
    





if __name__ == "__main__":
    main()