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:

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

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

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

count = {}

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict


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

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

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

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


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

print(*(d[ufd.root(i), ufr.root(i)] for i in range(n)))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self):
        return self.rank

class UnionFind2:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp


n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
uf2=UnionFind2(n)
q1,q2=[],[]
ans=[0]*n
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
    q1.append((a-1,b-1))
    ans[a-1]=1
    ans[b-1]=1

for i in range(l):
    a,b=map(int,raw_input().split())
    uf2.unite(a-1,b-1)
    if ans[a-1]==0: ans[a-1]=1
    if ans[b-1]==0: ans[b-1]=1
    if uf.same(a-1,b-1):
        ans[a-1]=2
        ans[b-1]=2

for i in q1:
    if uf2.same(i[0],i[1]):
        ans[i[0]]=2
        ans[i[1]]=2
print ' '.join(map(str,ans))

Submission status: Wrong Answer

Solution code:
n,k,l=map(int,raw_input().split())
e1=[[] for i in range(n)]
e2=[[] for i in range(n)]
for i in range(k):
    p,q=map(int,raw_input().split())
    e1[p-1].append(q-1)
    e1[q-1].append(p-1)
for i in range(l):
    p,q=map(int,raw_input().split())
    e2[p-1].append(q-1)
    e2[q-1].append(p-1)
num1=[0]*n
num2=[0]*n
def dfs1(x,i):
    num1[x]=i
    for node in e1[x]:
        if num1[node]==0:dfs1(node,i)
def dfs2(x,i):
    num2[x]=i
    for node in e2[x]:
        if num2[node]==0:dfs2(node,i)
cnt1=1
cnt2=1
for x in range(n):
    if num1[x]==0:dfs1(x,cnt1);cnt1+=1
    if num2[x]==0:dfs2(x,cnt2);cnt2+=1
dic={}
for x in range(n):
    t=num1[x]*10000+num2[x]
    if t in dic:dic[t]+=1
    else:dic[t]=1
ans=[0]*n
for x in range(n):
    ans[x]=dic[num1[x]*10000+num2[x]]
print ' '.join(map(str,ans))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self):
        return self.rank


class UnionFind2:
    def __init__(self, size2):
        self.rank2=[0]*size2
        self.par2 =range(size2)
        self.grp2 =size2

    def find(self, x2):
        if x2==self.par2[x2]: return x2

        self.par2[x2]=self.find(self.par2[x2])
        return self.par2[x2]

    def same(self, x2, y2): #2つの頂点が同じグループであるかを判定する
        return self.find(x2)==self.find(y2)

    def unite(self, x2, y2): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x2),self.find(y2)
        if x2==y2:
            return

        self.grp2-=1
        if self.rank2[x2]<self.rank2[y2]:
            self.par2[x2]=y2
        else:
            self.par2[y2]=x2
            if self.rank2[x2]==self.rank2[y2]:
                self.rank2[x2]+=1

    def group_num(self):
        return self.grp2
    def ra(self):
        return self.rank2



n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
uf2=UnionFind2(n)
q1,q2=[],[]
ans=[0]*n
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
    q1.append((a-1,b-1))
    ans[a-1]=1
    ans[b-1]=1

for i in range(l):
    a,b=map(int,raw_input().split())
    uf2.unite(a-1,b-1)
    if ans[a-1]==0: ans[a-1]=1
    if ans[b-1]==0: ans[b-1]=1
    if uf.same(a-1,b-1):
        ans[a-1]=2
        ans[b-1]=2

for i in q1:
    if uf2.same(i[0],i[1]):
        ans[i[0]]=2
        ans[i[1]]=2
print ' '.join(map(str,ans))

Submission status: Wrong Answer

Solution code:
# N K L
# p1 q1
# :
# pK qK
# r1 s1
# :
# rL sL
import numpy as np
N, K, L = map(int, raw_input().split())

# graph
Gp = dict()
Gq = dict()

# conn. components
p_con_todo = []
q_con_todo = []
p_con_list = []
q_con_list = []

# init
for n in range(1, N+1):
    p_con_todo.append(str(n))
    q_con_todo.append(str(n))
    Gp[str(n)] = []
    Gq[str(n)] = []
    
p_con_ids = np.zeros(N, dtype='int')
q_con_ids = np.zeros(N, dtype='int')

# input
for _ in range(K):
    p, q = map(int, raw_input().split())
    Gp[str(p)].append(str(q))
    Gp[str(q)].append(str(p))

for _ in range(L):
    p, q = map(int, raw_input().split())
    Gq[str(p)].append(str(q))
    Gq[str(q)].append(str(p))


    
# DFS
p_con_id = 0
while len(p_con_todo) > 0:
    p_con_id += 1
    ques = [p_con_todo[0]]
    conn = []
    while len(ques) > 0:
        n = ques.pop()
        conn.append(n)
        p_con_ids[int(n)-1] = p_con_id
        for m in Gp[n]:
            if m in conn:
                pass
            else:
                ques.append(m)
    p_con_todo = [n for n in p_con_todo if n not in conn]
    p_con_list.append(conn)

# DFS
q_con_id = 0
while len(q_con_todo) > 0:
    q_con_id += 1
    ques = [q_con_todo[0]]
    conn = []
    while len(ques) > 0:
        n = ques.pop()
        conn.append(n)
        q_con_ids[int(n)-1] = q_con_id
        for m in Gq[n]:
            if m in conn:
                pass
            else:
                ques.append(m)
    q_con_todo = [n for n in q_con_todo if n not in conn]
    q_con_list.append(conn)

# print p_con_ids
# print q_con_ids

# print anser
res_list = []
# for n in range(N):
#    res = int((np.ones(N)[(p_con_ids == p_con_ids[n]) * (q_con_ids == q_con_ids[n])]).sum())
#    res_list.append(str(res))
# print res_list
print " ".join(res_list)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self):
        return self.rank


class UnionFind2:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self):
        return self.rank



n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
uf2=UnionFind2(n)
q1,q2=[],[]
ans=[0]*n
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
    q1.append((a-1,b-1))
    ans[a-1]=1
    ans[b-1]=1
for i in range(l):
    a,b=map(int,raw_input().split())
    uf2.unite(a-1,b-1)
    q2.append((a-1,b-1))
    ans[a-1]=1
    ans[b-1]=1
    if uf.same(a-1,b-1):
        ans[a-1]=2
        ans[b-1]=2
for i in q1:
    if uf2.same(i[0],i[1]):
        ans[a-1]=2
        ans[b-1]=2
print ' '.join(map(str,ans))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self):
        return self.rank


class UnionFind2:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self):
        return self.rank



n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
uf2=UnionFind2(n)
q1,q2=[],[]
ans=[0]*n
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
    q1.append((a-1,b-1))
    ans[a-1]=1
    ans[b-1]=1
for i in range(l):
    a,b=map(int,raw_input().split())
    uf2.unite(a-1,b-1)
    q2.append((a-1,b-1))
    if uf.same(a-1,b-1):
        ans[a-1]=2
        ans[b-1]=2
for i in q1:
    if uf2.same(i[0],i[1]):
        ans[a-1]=2
        ans[b-1]=2
print ' '.join(map(str,ans))

Submission status: Wrong Answer

Solution code:
from scipy.stats import itemfreq


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

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

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

    def compress(self):
        return [i if v < 0 else self.find(self.table[i]) for i, v in enumerate(self.table)]

    @staticmethod
    def join(a, b):
        return [i + j * n for i, j in zip(a.compress(), b.compress())]


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

Submission status: Wrong Answer

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

##############################
road = [-1]*(N+1)  # 根であれば *そのグループの要素数(負)* が、子であれば親の番号が入る。
              # 初期値に -1 を入れておく
			  # v は頂点数

# 頂点 v の所属するグループを調べる
def root(v):
	if road[v] < 0:  # v が親の場合
		return v
	else:           # v が子の場合
		road[v] = root(road[v])  # 親のrootを調べる
		return road[v]

# 頂点 a と頂点 b をつなぐ。もともと同じグループのとき、False を返す
def connect(a, b):
	# まずはそれぞれ根の番号に置き換える
	ra = root(a)
	rb = root(b)
	if ra == rb:  # a と b がそもそも同じグループに属しているなら即終了
		return False
	
	# ra を大きなグループにしたいので、逆であれば入れ替える
	if road[ra] > road[rb]: # rbの方が要素数が多ければ
		tmp = ra
		ra  = rb 
		rb  = tmp

	# ra と rb を結合し、rb の親を ra とする
	road[ra] += road[rb]
	road[rb] = ra
	return True

# 頂点 a, b が同じグループであるかを調べる
def isConnect(a, b):
	return root(a) == root(b)

# 頂点 a を含むグループの頂点数を調べる
def size(a):
	return -road[root(a)]


##############################
rail = [-1]*(N+1)  # 根であれば *そのグループの要素数(負)* が、子であれば親の番号が入る。
              # 初期値に -1 を入れておく
			  # v は頂点数

# 頂点 v の所属するグループを調べる
def root2(v):
	if rail[v] < 0:  # v が親の場合
		return v
	else:           # v が子の場合
		rail[v] = root2(rail[v])  # 親のroot2を調べる
		return rail[v]

# 頂点 a と頂点 b をつなぐ。もともと同じグループのとき、False を返す
def connect2(a, b):
	# まずはそれぞれ根の番号に置き換える
	ra = root2(a)
	rb = root2(b)
	if ra == rb:  # a と b がそもそも同じグループに属しているなら即終了
		return False
	
	# ra を大きなグループにしたいので、逆であれば入れ替える
	if rail[ra] > rail[rb]: # rbの方が要素数が多ければ
		tmp = ra
		ra  = rb 
		rb  = tmp

	# ra と rb を結合し、rb の親を ra とする
	rail[ra] += rail[rb]
	rail[rb] = ra
	return True

# 頂点 a, b が同じグループであるかを調べる
def isConnect2(a, b):
	return root2(a) == root2(b)

# 頂点 a を含むグループの頂点数を調べる
def size2(a):
	return -rail[root2(a)]




##
ans = [1]*(N+1)

for i in range(K):
	p, q = map(int, input().split())
	connect(p, q)

for i in range(L):
	r, s = map(int, input().split())
	if isConnect(r, s):
		connect2(r, s)

for i in range(1, N):
	print(size2(i), end = " ")
print(size2(N))

Submission status: Wrong Answer

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


road = [-1]*(N+1)  # 根であれば *そのグループの要素数(負)* が、子であれば親の番号が入る。
              # 初期値に -1 を入れておく
			  # v は頂点数

# 頂点 v の所属するグループを調べる
def root(v):
	if road[v] < 0:  # v が親の場合
		return v
	else:           # v が子の場合
		road[v] = root(road[v])  # 親のrootを調べる
		return road[v]

# 頂点 a と頂点 b をつなぐ。もともと同じグループのとき、False を返す
def connect(a, b):
	# まずはそれぞれ根の番号に置き換える
	ra = root(a)
	rb = root(b)
	if ra == rb:  # a と b がそもそも同じグループに属しているなら即終了
		return False
	
	# ra を大きなグループにしたいので、逆であれば入れ替える
	if road[ra] > road[rb]: # rbの方が要素数が多ければ
		tmp = ra
		ra  = rb 
		rb  = tmp

	# ra と rb を結合し、rb の親を ra とする
	road[ra] += road[rb]
	road[rb] = ra
	return True

# 頂点 a, b が同じグループであるかを調べる
def isConnect(a, b):
	return root(a) == root(b)

# 頂点 a を含むグループの頂点数を調べる
def size(a):
	return -road[root(a)]


##
ans = [1]*(N+1)

for i in range(K):
	p, q = map(int, input().split())
	connect(p, q)

for i in range(L):
	r, s = map(int, input().split())
	if isConnect(r, s):
		ans[r] += 1
		ans[s] += 1

for i in range(1, N):
	print(ans[i], end = " ")
print(ans[-1])

Submission status: Wrong Answer

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

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

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

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

    def tree_number(self):
        return self.tree_num

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

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

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

        self.par[x]=self.find(self.par[x])
        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self,x):
        return self.rank[x]



n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
ans=['0']*n
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
    ans[a-1]='1'
    ans[b-1]='1'
for i in range(l):
    a,b=map(int,raw_input().split())
    if ans[a-1]=='0':
        ans[a-1]='1'
    if ans[b-1]=='0':
        ans[b-1]='1'
    if uf.same(a-1,b-1):
        ans[a-1]='2'
        ans[b-1]='2'

print ' '.join(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
n, k, l = map(int, raw_input().split())

road = defaultdict(list)
rail = defaultdict(list)
for i in xrange(k):
    pi, qi = map(int, raw_input().split())
    pi -= 1
    qi -= 1
    road[pi].append(qi)
    road[qi].append(pi)

for i in xrange(l):
    si, ri = map(int, raw_input().split())
    si -= 1
    ri -= 1
    rail[si].append(ri)
    rail[ri].append(si)

line = rail
visited = [0] * n
for i in xrange(n):
    can_visit = set(line[i])
    can_visit.add(i)
    to_visit = line[i]
    visited = [i]
    while to_visit:
        place = to_visit.pop()
        if place in visited:
            continue
        can_visit |= set(line[place])
        to_visit += line[place]
        visited.append(place)
    # print can_visit
    can_visit &= set(road[i])
    print len(can_visit) + 1,

Submission status: Wrong Answer

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

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

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

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

    def tree_number(self):
        return self.tree_num

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

n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
for i in xrange(k):
    p,q=map(int,raw_input().split())
    p-=1;q-=1
    uf.unite(p,q)
ans=[1]*n
for i in xrange(l):
    p,q=map(int,raw_input().split())
    p-=1;q-=1
    if uf.same(p,q):
        ans[p]+=1
        ans[q]+=1
    #uf.unite(p,q)
print " ".join(map(str,ans))

Submission status: Wrong Answer

Solution code:
class UnionFind:

    def __init__(self, size):
        # 負の値はルート (集合の代表) で集合の個数
        # 正の値は次の要素を表す
        self.size = size
        self.table = [-1 for _ in range(size)]

    def find(self, x):
        # 集合の代表を求める
        children = []
        while self.table[x] >= 0:
            children.append(x)
            x = self.table[x]
        for c in children:
            self.table[c] = x
        return x

    def union(self, x, y):
        # 併合
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] >= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
        return self.table[s1]

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

for i in range(k):
    p,q = map(int, input().split())
    z[(p,q)] = True
ut = UnionFind(n+1)
for i in range(l):
    p,q = map(int, input().split())
    if (p,q) in z:
        ut.union(p,q)
table = ut.table[:]

print(*[-table[ut.find(i+1)] for i in range(n)], sep=' ')