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
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

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

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

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

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

N, K, L = mapint()
uf_road = UnionFind(N)
for _ in range(K):
    x, y = mapint()
    uf_road.union(x-1, y-1)
uf_rail = UnionFind(N)
for _ in range(L):
    x, y = mapint()
    if uf_road.same(x-1, y-1):
        uf_rail.union(x-1, y-1)

ans = []
for i in range(N):
    ans.append(str(uf_rail.size(i)))
print(' '.join(ans))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict,deque
import math
class UnionFind:
    def __init__(self, N):
        self.parent = [i for i in range(N)]
        self.rank = [0]*N
        self.count = 0
    def root(self, a):
        if self.parent[a]==a:
            return a
        else:
            self.parent[a]=self.root(self.parent[a])
            return self.parent[a]
    def size(x):
        return -par[root(x)]

    def is_same(self, a, b):
        return self.root(a)==self.root(b)
    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb: return

        if self.rank[ra] < self.rank[rb]:
            self.parent[ra] = rb
        else:
            self.parent[rb] = ra
            if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1
        self.count += 1
def main():
    n,k,l=map(int, input().split())
    uf1 = UnionFind(n)
    res = [1]*n

    for i in range(k):
        p,q=map(int, input().split())
        uf1.unite(p-1,q-1)
    for i in range(l):
        r,s=map(int, input().split())
        if(uf1.is_same(r-1,s-1)):
            res[r-1]+=1
            res[s-1]+=1

    print(*res)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N,K,L = map(int, input().split())
road = [list(map(int,input().split())) for _ in range(K)]
trail = [list(map(int, input().split())) for _ in range(L)]
city = [[0]*N for _ in range(N)]
for i in range(K):
    a = road[i][0] - 1
    b = road[i][1] - 1
    city[a][b] += 1
    city[b][a] += 1
for i in range(L):
    a = trail[i][0] - 1
    b = trail[i][1] - 1
    if city[a][b] ==0:
        city[a][b] += 1
        city[b][a] += 1

result = [str(sum(city[i])) for i in range(N)]
result = ' '.join(result)
print(result)
#for answer in result:    
#    print(answer)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N,K,L = map(int, input().split())
road = [list(map(int,input().split())) for _ in range(K)]
trail = [list(map(int, input().split())) for _ in range(L)]
city = [[0]*N for _ in range(N)]
for i in range(K):
    a = road[i][0] - 1
    b = road[i][1] - 1
    city[a][b] += 1
    city[b][a] += 1
for i in range(L):
    a = trail[i][0] - 1
    b = trail[i][1] - 1
    if city[a][b] ==0:
        city[a][b] += 1
        city[b][a] += 1
#print(city)
result = [sum(city[i]) for i in range(N)]
#print(result)
for answer in result:
    print(answer,end=' ')

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N,K,L = map(int, input().split())
road = [list(map(int,input().split())) for _ in range(K)]
trail = [list(map(int, input().split())) for _ in range(L)]
city = [[0]*N for _ in range(N)]
for i in range(K):
    a = road[i][0] - 1
    b = road[i][1] - 1
    city[a][b] += 1
    city[b][a] += 1
for i in range(L):
    a = trail[i][0] - 1
    b = trail[i][1] - 1
    if city[a][b] ==0:
        city[a][b] += 1
        city[b][a] += 1
print(city)
result = [sum(city[i]) for i in range(N)]
print(result)
for answer in result:
    print(answer,end=' ')

Submission status: Wrong Answer

Solution code:
class UnionFind():

    def __init__(self, n):
        self.n = n
        self.parent = [i for i in range(n)]
        self.rank = [0 for i in range(n)]
        self.mems = [set() for i in range(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):
        if x != y:
            self.mems[y].add(x)
            self.mems[x].add(y)

        x = self.find(x)
        y = self.find(y)

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

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

    def memsInGroup(self, x):
        return self.mems[x]

    def sizeOfGroup(self, x):
        return len(self.memsInGroup(x))


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

road = UnionFind(N)
train = UnionFind(N)

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

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

for i in range(N):
    conByRoad = road.memsInGroup(i)
    conByTrain = train.memsInGroup(i)
    # print(conByRoad, conByTrain)

    ans = len(set(conByRoad) & set(conByTrain))+1
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

class UnionFind():
    def __init__(self, n=0):
        self.d = [-1]*n
    
    def find(self, x):
        if self.d[x] < 0: return x
        self.d[x] = self.find(self.d[x])
        return self.d[x]

    def unite(self, x, y):
        x,y=self.find(x),self.find(y)
        if x==y:return False
        if self.d[x] > self.d[y]: x,y=y,x
        self.d[x] += self.d[y]
        self.d[y] = x
        return True

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

N,K,L=map(int,input().split())
uf1 = UnionFind(N+1)
uf2 = UnionFind(N+1)
for i in range(K):
  p,q=map(int,input().split())
  uf1.unite(p,q)
  
for i in range(L):
  r,s=map(int,input().split())
  uf2.unite(r,s)
  
groups1,groups2=defaultdict(list),defaultdict(list)
for i in range(1,N+1):
  if uf1.d[i]>0:
    groups1[uf1.d[i]].append(i)
  if uf2.d[i]>0:
    groups2[uf2.d[i]].append(i)
    
total_groups=[]
for i,k1 in enumerate(groups1.keys()):
  groups1[k1].append(k1)
  for k2 in groups2.keys():
    if i == 0:groups2[k2].append(k2)
    g = tuple(set(groups1[k1]).intersection(set(groups2[k2])))
    if len(g)>1:total_groups.append(g)
    
ans = [1]*N
for g in total_groups:
  for a in g:
    ans[a-1] += len(g)-1
    
print(*ans)

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
A = []
B = []
ans = [1 for i in range(N)]

for i in range(K):
    p, q = map(int, input().split())
    X = {p, q}
    for j in range(len(A)):
        if X in A[j]:
            break
        elif p in A[j] or q in A[j]:
            A[j] |= X
    else:
        A.append(X)
for i in range(L):
    r, s = map(int, input().split())
    Y = {r, s}
    for j in range(len(B)):
        if Y in B[j]:
            break
        elif r in B[j] or s in B[j]:
            B[j] |= Y
            break
    else:
        B.append(Y)
for a in A:
    for b in B:
        if len(a & b) != 0:
            n = len(a & b)
            for i in a & b:
                ans[i-1] = n
print(*ans)

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
city = [{"path":{i},"train":{i}} for i in range(N)]
for i in range(K):
    p, q = map(int, input().split())
    together = city[p-1]["path"] | city[q-1]["path"]
    city[p-1]["path"] = together
    city[q-1]["path"] = together
for i in range(L):
    r, s = map(int, input().split())
    together = city[r-1]["train"] | city[s-1]["train"]
    city[r-1]["train"] = together
    city[s-1]["train"] = together
else:
    del together
for i in range(N):
    print(len(city[i]["path"]&city[i]["train"]), end=" ")

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
city = [{"path":{i},"train":{i}} for i in range(N)]
for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["path"].add(q-1)
    together = city[p-1]["path"] | city[q-1]["path"]
    city[p-1]["path"] = together
    city[q-1]["path"] = together
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["train"].add(s-1)
    together = city[r-1]["train"] | city[s-1]["train"]
    city[r-1]["train"] = together
    city[s-1]["train"] = together
else:
    del together
for i in range(N):
    print(len(city[i]["path"]&city[i]["train"]), end=" ")

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
city = [{"path":{i},"train":{i}} for i in range(N)]
for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["path"].add(q-1)
    city[q-1]["path"].add(p-1)
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["train"].add(s-1)
    city[s-1]["train"].add(r-1)
done = set()
for i in range(N):
    for x in city[i]["path"]-done:
        city[i]["path"] = city[i]["path"] | city[x]["path"]
        city[x]["path"] = city[i]["path"]
    for y in city[i]["train"]-done:
        city[i]["train"] = city[i]["train"] | city[y]["train"]
        city[y]["train"] = city[i]["train"]
    done.add(i)
for i in range(N):
    print(len(city[i]["path"]&city[i]["train"]), end=" ")

Submission status: Wrong Answer

Solution code:
N, K, L = map(int, input().split())
city = [{"path":{i},"train":{i}} for i in range(N)]
for i in range(K):
    p, q = map(int, input().split())
    city[p-1]["path"].add(q-1)
    city[q-1]["path"].add(p-1)
for i in range(L):
    r, s = map(int, input().split())
    city[r-1]["train"].add(s-1)
    city[s-1]["train"].add(r-1)
for i in range(N):
    for x in city[i]["path"]:
        city[i]["path"] = city[i]["path"] | city[x]["path"]
    for y in city[i]["train"]:
        city[i]["train"] = city[i]["train"] | city[y]["train"]
for i in range(N):
    print(len(city[i]["path"]&city[i]["train"]), end=" ")

Submission status: Wrong Answer

Solution code:
import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy


class UnionFind:

    def __init__(self, n: int):
        self._n = n
        self._parents = [i for i in range(n)]
        self._size = [1 for _ in range(n)]

    def unite(self, x: int, y: int) -> None:
        px = self.find(x)
        py = self.find(y)

        # 一致していないときはリンクをつける
        if px != py:
            self._link(px, py)

    def _link(self, x: int, y: int):
        if self._size[x] < self._size[y]:
            self._parents[x] = y
            self._size[y] += self._size[x]
        else:
            self._parents[y] = x
            self._size[x] += self._size[y]

    def same(self, x: int, y: int) -> bool:
        px = self.find(x)
        py = self.find(y)
        return px == py

    def find(self, x: int) -> int:
        if self._parents[x] == x:
            return x

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

    def size(self, x: int):
        return self._size[self.find(self._parents[x])]

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

road = UnionFind(N + 1)
rail = UnionFind(N + 1)
share = UnionFind(N + 1)

roads = [list(map(int, input().split())) for _ in range(K)]
rails = [list(map(int, input().split())) for _ in range(L)]

for i in range(K):
    p, q = roads[i]
    road.unite(p, q)

for i in range(L):
    r, s = rails[i]
    rail.unite(r, s)

for i in range(N + 1):
    if rail.same(i, road.find(i)):
        share.unite(i, road.find(i))

    if road.same(i, rail.find(i)):
        share.unite(i, rail.find(i))

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

print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy


class UnionFind:

    def __init__(self, n: int):
        self._n = n
        self._parents = [i for i in range(n)]
        self._size = [1 for _ in range(n)]

    def unite(self, x: int, y: int) -> None:
        px = self.find(x)
        py = self.find(y)

        # 一致していないときはリンクをつける
        if px != py:
            self._link(px, py)

    def _link(self, x: int, y: int):
        if self._size[x] < self._size[y]:
            self._parents[x] = y
            self._size[y] += self._size[x]
        else:
            self._parents[y] = x
            self._size[x] += self._size[y]

    def same(self, x: int, y: int) -> bool:
        px = self.find(x)
        py = self.find(y)
        return px == py

    def find(self, x: int) -> int:
        if self._parents[x] == x:
            return x

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

    def size(self, x: int):
        return self._size[self.find(self._parents[x])]

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

road = UnionFind(N + 1)
rail = UnionFind(N + 1)
share = UnionFind(N + 1)

roads = [list(map(int, input().split())) for _ in range(K)]
rails = [list(map(int, input().split())) for _ in range(L)]

for i in range(K):
    p, q = roads[i]
    road.unite(p, q)

for i in range(L):
    r, s = rails[i]
    rail.unite(r, s)
    if road.same(r, s):
        share.unite(r, s)

for i in range(K):
    p, q = roads[i]
    if rail.same(p, q):
        share.unite(p, q)

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

print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy


class UnionFind:

    def __init__(self, n: int):
        self._n = n
        self._parents = [i for i in range(n)]
        self._size = [1 for _ in range(n)]

    def unite(self, x: int, y: int) -> None:
        px = self.find(x)
        py = self.find(y)

        # 一致していないときはリンクをつける
        if px != py:
            self._link(px, py)

    def _link(self, x: int, y: int):
        if self._size[x] < self._size[y]:
            self._parents[x] = y
            self._size[y] += self._size[x]
        else:
            self._parents[y] = x
            self._size[x] += self._size[y]

    def same(self, x: int, y: int) -> bool:
        px = self.find(x)
        py = self.find(y)
        return px == py

    def find(self, x: int) -> int:
        if self._parents[x] == x:
            return x

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

    def size(self, x: int):
        return self._size[self.find(self._parents[x])]

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

road = UnionFind(N + 1)
rail = UnionFind(N + 1)
share = UnionFind(N + 1)

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

for i in range(L):
    r, s = map(int, input().split())
    rail.unite(r, s)
    if road.same(r, s):
        share.unite(r, s)

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

print(*ans)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self,n):
        self.n=n
        self.parent=[i for i in range(n)]
        self.rank=[1]*n#木の高さ
        self.size=[1]*n#size[i]はiを根とするグループのサイズ

    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:
            if self.rank[x]<self.rank[y]:#ランクの比較
                self.parent[x]=y
                self.size[y]+=self.size[x]
            else:
                self.parent[y]=x
                self.size[x]+=self.size[y]
                if self.rank[x]==self.rank[y]:
                    self.rank[x]+=1

    def group_size(self,x):#ｘが属する集合の大きさ
        return self.size[self.find(x)]

    def is_same(self,x,y):#ｘ、ｙが同じ集合に属するかを判定する
        return self.find(x)==self.find(y)

n,k,l=map(int,input().split())
road=UnionFind(n)
rail=UnionFind(n)
ans=[0]*(n)
for i in range(k):
    p,q=map(int,input().split())
    road.unite(p-1,q-1)

for i in range(l):
    r,s=map(int,input().split())
    if not(road.is_same(r-1,s-1)):
        ans[r-1]-=1
        ans[s-1]-=1
    rail.unite(r-1,s-1)

for i in range(n):
    ans[i] += min(road.group_size(i), rail.group_size(i))
    if road.group_size(i)==1 or rail.group_size(i)==1:
        ans[i]=1
    print(ans[i])

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self,n):
        self.n=n
        self.parent=[i for i in range(n)]
        self.rank=[1]*n#木の高さ
        self.size=[1]*n#size[i]はiを根とするグループのサイズ

    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:
            if self.rank[x]<self.rank[y]:#ランクの比較
                self.parent[x]=y
                self.size[y]+=self.size[x]
            else:
                self.parent[y]=x
                self.size[x]+=self.size[y]
                if self.rank[x]==self.rank[y]:
                    self.rank[x]+=1

    def group_size(self,x):#ｘが属する集合の大きさ
        return self.size[self.find(x)]

n,k,l=map(int,input().split())
road=UnionFind(n)
rail=UnionFind(n)
for i in range(k):
    p,q=map(int,input().split())
    road.unite(p-1,q-1)

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

for i in range(n):
    print(min(road.group_size(i),rail.group_size(i)))

Submission status: Wrong Answer

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

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

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

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

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

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n,k,l=map(int,input().split())
uf1=UnionFind(n+1)
for i in range(k):
  a,b=map(int,input().split())
  uf1.union(a,b)
uf2=UnionFind(n+1)
for i in range(l):
  a,b=map(int,input().split())
  if uf1.same(a,b):
    uf2.union(a,b)
for i in range(1,n+1):
  print(uf2.size(i))

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
#     print(s)
#     print(label)
#     return [label[s[i]-1] for i in range(n)] 
           
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])
    c=0
    s=[0]*n
    stack=deque()
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            stack.clear()
            stack.append(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[i] for i in range(n)] 

def components2(n,k,e):
    es=deque(set((edge[0],edge[1])) for edge in e)
    c=0
    s=deque()
    stack=deque()
    while es:
        f=es.pop()
        stack.clear()
        while es:
            l=len(es)
            g=es.pop()
            if g&f:
                f|=g
            else:
                stack.append(g)
            if l==len(stack):
                s.append(f)
                break
            es=stack
    t=[0]*n
    c=0
    while s:
        for x in s.pop():
            t[x-1]=c
        c+=1
    return t
                
                
        
        
def main(n,k,l,e1,e2):
    d1=components2(n,k,e1)
    d2=components2(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
    lbl=[0]*n
    for i in range(1,n+1):
        if s[i-1]==0:
            c+=1
            lbl[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:
                        lbl[s[wn-1]-1]=c
    return [lbl[s[i]-1] for i in range(n)] 
           
def components2(n,k,e):
    ed=defaultdict(lambda:deque())
    for edge in e:
        ed[edge[0]].append(edge[1])
        ed[edge[1]].append(edge[0])
    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[i] for i 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[i]-1] for i 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)