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: Time Limit Exceeded

Solution code:
def main():  
  #Union Find

  #xの根を求める
  def find(x):
      if par[x] < 0:
          return x
      else:
          par[x] = find(par[x])
          return par[x]
  #xとyの属する集合の併合
  def unite(x,y):
      x = find(x)
      y = find(y)

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

  def find2(x):
    if pa[x] < 0:
        return x
    else:
        pa[x] = find2(pa[x])
        return pa[x]

  import sys
  input = sys.stdin.readline

  n,k,l = [int(i) for i in input().split()]
  par = [-1]*n
  pa = [-1]*n
  ans = [0]*n

  for i in range(k):
    p,q = [int(i) for i in input().split()]
    unite(p-1,q-1)

  def unite2(x,y):
      x = find2(x)
      y = find2(y)
      if x == y:
          return False
      else:
          if pa[x] > pa[y]:
              x,y = y,x
          pa[x] += pa[y]
          pa[y] = x
          return True

  for i in range(l):
    r,s = [int(i) for i in input().split()]
    unite2(r-1,s-1)

  import collections
  chk = [find(i)*10**6+find2(i) for i in range(n)]
  
  for i in range(n):
    c = collections.Counter(chk)
    ans[i] += c[chk[i]]
  ans = list(map(str,ans))
  print(' '.join(ans))
  
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():  
  #Union Find

  #xの根を求める
  def find(x):
      if par[x] < 0:
          return x
      else:
          par[x] = find(par[x])
          return par[x]
  #xとyの属する集合の併合
  def unite(x,y):
      x = find(x)
      y = find(y)

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

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

  def find2(x):
    if pa[x] < 0:
        return x
    else:
        pa[x] = find2(pa[x])
        return pa[x]

  #根なら-size,子なら親の頂点

  import sys
  input = sys.stdin.readline

  n,k,l = [int(i) for i in input().split()]
  par = [-1]*n
  pa = [-1]*n
  ans = [0]*n

  for i in range(k):
    p,q = [int(i) for i in input().split()]
    unite(p-1,q-1)

  def unite2(x,y):
      x = find2(x)
      y = find2(y)
      if x == y:
          return False
      else:
          if pa[x] > pa[y]:
              x,y = y,x
          pa[x] += pa[y]
          pa[y] = x
          return True

  for i in range(l):
    r,s = [int(i) for i in input().split()]
    unite2(r-1,s-1)

  import collections
  chk = collections.deque([])
  for i in range(n):
    chk_append = chk.append
    chk_append(find(i)*10**6+find2(i))
  chk = list(chk)
  for i in range(n):
    c = collections.Counter(chk)
    ans[i] += c[chk[i]]

  ans = list(map(str,ans))
  print(' '.join(ans))
  
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():  
  #Union Find

  #xの根を求める
  def find(x):
      if par[x] < 0:
          return x
      else:
          par[x] = find(par[x])
          return par[x]
  #xとyの属する集合の併合
  def unite(x,y):
      x = find(x)
      y = find(y)

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

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

  def find2(x):
    if pa[x] < 0:
        return x
    else:
        pa[x] = find2(pa[x])
        return pa[x]

  #根なら-size,子なら親の頂点

  import sys
  input = sys.stdin.readline

  n,k,l = [int(i) for i in input().split()]
  par = [-1]*n
  pa = [-1]*n
  ans = [0]*n

  for i in range(k):
    p,q = [int(i) for i in input().split()]
    unite(p-1,q-1)

  def unite2(x,y):
      x = find2(x)
      y = find2(y)
      if x == y:
          return False
      else:
          if pa[x] > pa[y]:
              x,y = y,x
          pa[x] += pa[y]
          pa[y] = x
          return True

  for i in range(l):
    r,s = [int(i) for i in input().split()]
    unite2(r-1,s-1)

  #print(par,pa)
  chk = []
  for i in range(n):
    chk_append = chk.append
    chk_append(find(i)*10**6+find2(i))

  import collections
  for i in range(n):
    c = collections.Counter(chk)
    ans[i] += c[chk[i]]

  ans = list(map(str,ans))
  print(' '.join(ans))
  
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#Union Find
 
#xの根を求める
def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
#xとyの属する集合の併合
def unite(x,y):
    x = find(x)
    y = find(y)
    
    if x == y:
        return False
    else:
        #sizeの大きいほうがx
        if par[x] > par[y]:
            x,y = y,x
        par[x] += par[y]
        par[y] = x
        return True

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

def find2(x):
  if pa[x] < 0:
      return x
  else:
      pa[x] = find2(pa[x])
      return pa[x]

#根なら-size,子なら親の頂点
n,k,l = [int(i) for i in input().split()]
par = [-1]*n
pa = [-1]*n
ans = [0]*n

for i in range(k):
  p,q = [int(i) for i in input().split()]
  unite(p-1,q-1)

def unite2(x,y):
    x = find2(x)
    y = find2(y)
    if x == y:
        return False
    else:
        if pa[x] > pa[y]:
            x,y = y,x
        pa[x] += pa[y]
        pa[y] = x
        return True
  
for i in range(l):
  r,s = [int(i) for i in input().split()]
  unite2(r-1,s-1)

#print(par,pa)
chk = []
for i in range(n):
  chk_append = chk.append
  chk_append((find(i),find2(i)))
  
import collections
for i in range(n):
  c = collections.Counter(chk)
  ans[i] += c[chk[i]]
  
ans = list(map(str,ans))
print(' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
#Union Find
 
#xの根を求める
def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
#xとyの属する集合の併合
def unite(x,y):
    x = find(x)
    y = find(y)
    
    if x == y:
        return False
    else:
        #sizeの大きいほうがx
        if par[x] > par[y]:
            x,y = y,x
        par[x] += par[y]
        par[y] = x
        return True

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

def find2(x):
  if pa[x] < 0:
      return x
  else:
      pa[x] = find2(pa[x])
      return pa[x]

#根なら-size,子なら親の頂点
n,k,l = [int(i) for i in input().split()]
par = [-1]*n
pa = [-1]*n
ans = [0]*n
pq = []

for i in range(k):
  p,q = [int(i) for i in input().split()]
  unite(p-1,q-1)
  pq_append = pq.append
  pq_append([p-1,q-1])

def unite2(x,y):
    x = find2(x)
    y = find2(y)
    if x == y:
        return False
    else:
        if pa[x] > pa[y]:
            x,y = y,x
        pa[x] += pa[y]
        pa[y] = x
        return True
  
for i in range(l):
  r,s = [int(i) for i in input().split()]
  unite2(r-1,s-1)

#print(par,pa)
chk = []
for i in range(n):
  chk_append = chk.append
  chk_append((find(i),find2(i)))
  
import collections
for i in range(n):
  c = collections.Counter(chk)
  ans[i] += c[chk[i]]
  
ans = list(map(str,ans))
print(' '.join(ans))

Submission status: Time Limit Exceeded

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())
import sys
input=sys.stdin.readline
n,k,l = map(int, input().split())
uf_road = UnionFind(n)
uf_train = UnionFind(n)
for i in range(k):
    p,q=list(map(int, input().split()))
    uf_road.union(p-1, q-1)
for i in range(l):
    p,q=list(map(int, input().split()))
    uf_train.union(p-1, q-1)

ans=[0]*n
for i in range(n):
    if ans[i]!=0:
        continue
    mem1=set(uf_road.members(i))
    mem2=set(uf_train.members(i))
    inter=mem1 & mem2
    int_num=len(inter)
    for tmp in inter:
        ans[tmp]=int_num
print(*ans)

Submission status: Time Limit Exceeded

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())
R=UnionFind(n)
T=UnionFind(n)
for i in range(k):
  p,k=map(int,input().split())
  p=p-1
  k=k-1
  R.union(p,k)
for i in range(l):
  r,s=map(int,input().split())
  r=r-1
  s=s-1
  T.union(r,s)
ans=[0]*n
for i in range(len(R.roots())):
  A=R.members(R.roots()[i])
  AA=set(A)
  a=len(A)
  for j in range(len(A)):
    B=T.members(A[j])
    BB=set(B)
    b=len(B)
    ans[A[j]]=a+b-len(AA|BB)
print(*ans)

Submission status: Time Limit Exceeded

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())
R=UnionFind(n)
T=UnionFind(n)
for i in range(k):
  p,k=map(int,input().split())
  p=p-1
  k=k-1
  R.union(p,k)
for i in range(l):
  r,s=map(int,input().split())
  r=r-1
  s=s-1
  T.union(r,s)
for i in range(n):
  print(len(R.members(i))+len(T.members(i))-len(set(R.members(i))|set(T.members(i))),end=" ")
print()

Submission status: Time Limit Exceeded

Solution code:
import sys


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


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

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

    def unite(self, x, y):
        x = self.root(x)
        y = self.root(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.root(x)]

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

    def members(self, x):
        root = self.root(x)
        return [i for i in range(self.n) if self.root(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())


def main():

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

    for _ in range(K):
        a, b = map(int, input().split())
        highway.unite(a - 1, b - 1)

    for _ in range(L):
        a, b = map(int, input().split())
        railroad.unite(a - 1, b - 1)

    ans = [1] * N
    for i in range(N - 1):
        for j in range(i + 1, N):
            if highway.same(i, j) and railroad.same(i, j):
                ans[i] += 1
                ans[j] += 1
    print(' '.join(map(str, ans)))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

    def unite(self, x, y):
        x = self.root(x)
        y = self.root(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.root(x)]

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

    def members(self, x):
        root = self.root(x)
        return [i for i in range(self.n) if self.root(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())


def main():

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

    for _ in range(K):
        a, b = map(int, input().split())
        highway.unite(a - 1, b - 1)

    for _ in range(L):
        a, b = map(int, input().split())
        railroad.unite(a - 1, b - 1)

    ans = [1] * N
    for i in range(N - 1):
        for j in range(i + 1, N):
            if highway.same(i, j) and railroad.same(i, j):
                ans[i] += 1
                ans[j] += 1
    print(' '.join(map(str, ans)))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,k,l = map(int,input().split())
class UnionFindPathCompression():
    def __init__(self, n):
        self.n = n
        self.parents = list(range(n))

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

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

        if x == y:
            return

        self.parents[y] = x
        
    def same(self, x, y):
        return self.find(x) == self.find(y)
      
    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
      
load = UnionFindPathCompression(n)
train = UnionFindPathCompression(n)
for i in range(k):
  p,q = map(int,input().split())
  load.union(p-1,q-1)
for j in range(l):
  r,s = map(int,input().split())
  train.union(r-1,s-1)
  
result_list = []
for a in range(n):
  load_mem = load.members(a)
  train_mem = train.members(a)
  result = set(load_mem) & set(train_mem)
  result_list.append(len(result))
  
print(*result_list)

Submission status: Time Limit Exceeded

Solution code:
n,k,l = map(int,input().split())
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]

load = UnionFind(n)
train = UnionFind(n)
for i in range(k):
  p,q = map(int,input().split())
  load.union(p-1,q-1)
for j in range(l):
  r,s = map(int,input().split())
  train.union(r-1,s-1)
  
result_list = []
for a in range(n):
  load_mem = load.members(a)
  train_mem = train.members(a)
  result = set(load_mem) & set(train_mem)
  result_list.append(len(result))
  
print(*result_list)

Submission status: Time Limit Exceeded

Solution code:
class UnionFind:
    def __init__(self,n):
        super().__init__()
        self.par = [-1]*n
        self.rank = [0]*n
        self.tsize = [1]*n

    
    def root(self,x):
        if self.par[x] == -1:
            return x 
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

    def unite(self, x, y):
        x_r = self.root(x)
        y_r = self.root(y)
        
        if self.rank[x_r]>self.rank[y_r]:
            self.par[y_r] = x_r

        elif self.rank[x_r]<self.rank[y_r]:
            self.par[x_r] = y_r

        elif x_r != y_r:
            self.par[y_r] = x_r
            self.rank[x_r] += 1

        if x_r != y_r:
            size = self.tsize[x_r]+self.tsize[y_r]
            self.tsize[x_r] = size
            self.tsize[y_r] = size

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

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

def main():
    n,k,l = tuple([int(t)for t in input().split()])

    uf_k = UnionFind(n)
    uf_l = UnionFind(n)


    pq = [[int(t)-1 for t in input().split()]for _ in [0]*k]
    for p,q in pq:
        uf_k.unite(p,q)

    rs = [[int(t)-1 for t in input().split()]for _ in [0]*l]
    for r,s in rs:
        uf_l.unite(r,s)

    k_set = set([])
    l_set = set([])

    for i in range(n):
        k_set.add(uf_k.root(i))
        l_set.add(uf_l.root(i))

    k_dict = {}
    l_dict = {}
    for e in k_set:
        k_dict[e] = set([])
    for e in l_set:
        l_dict[e] = set([])

    for i in range(n):
        k_dict[uf_k.root(i)].add(i)
        l_dict[uf_l.root(i)].add(i)

    ans = []
    for i in range(n):
        k_s = k_dict[uf_k.root(i)]
        l_s = l_dict[uf_l.root(i)]

        ans.append(len(l_s.intersection(k_s)))

    print(*ans)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
class UnionFind:
    def __init__(self,n):
        super().__init__()
        self.par = [-1]*n
        self.rank = [0]*n
        self.tsize = [1]*n

    
    def root(self,x):
        if self.par[x] == -1:
            return x 
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

    def unite(self, x, y):
        x_r = self.root(x)
        y_r = self.root(y)
        
        if self.rank[x_r]>self.rank[y_r]:
            self.par[y_r] = x_r

        elif self.rank[x_r]<self.rank[y_r]:
            self.par[x_r] = y_r

        elif x_r != y_r:
            self.par[y_r] = x_r
            self.rank[x_r] += 1

        if x_r != y_r:
            size = self.tsize[x_r]+self.tsize[y_r]
            self.tsize[x_r] = size
            self.tsize[y_r] = size

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

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

def main():
    n,k,l = tuple([int(t)for t in input().split()])

    uf_k = UnionFind(n)
    uf_l = UnionFind(n)


    pq = [[int(t)-1 for t in input().split()]for _ in [0]*k]
    for p,q in pq:
        uf_k.unite(p,q)

    rs = [[int(t)-1 for t in input().split()]for _ in [0]*l]
    for r,s in rs:
        uf_l.unite(r,s)

    k_set = set([])
    l_set = set([])

    for i in range(n):
        k_set.add(uf_k.root(i))
        l_set.add(uf_l.root(i))

    k_dict = {}
    l_dict = {}
    for e in k_set:
        k_dict[e] = set([])
    for e in l_set:
        l_dict[e] = set([])

    for i in range(n):
        k_dict[uf_k.root(i)].add(i)
        l_dict[uf_l.root(i)].add(i)

    ans = []
    for i in range(n):
        k_s = k_dict[uf_k.root(i)]
        l_s = l_dict[uf_l.root(i)]

        ans.append(len(l_s.intersection(k_s)))

    print(*ans)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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


def MAP(): return map(int, input().split())
def ZIP(n): return zip(*(MAP() for _ in range(n)))

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

for i in range(K):
    node1, node2 = list(map(int, input().split()))
    uf_road.union(node1 - 1, node2 - 1)

for i in range(L):
    node1, node2 = list(map(int, input().split()))
    uf_train.union(node1 - 1, node2 - 1)

ans = [len(set(uf_road.members(i)) & set(uf_train.members(i))) for i in range(N)]
print(*ans)

Submission status: Time Limit Exceeded

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())


def MAP(): return map(int, input().split())
def ZIP(n): return zip(*(MAP() for _ in range(n)))

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

for i in range(K):
    node1, node2 = list(map(int, input().split()))
    uf_road.union(node1 - 1, node2 - 1)

for i in range(L):
    node1, node2 = list(map(int, input().split()))
    uf_train.union(node1 - 1, node2 - 1)

ans = [len(set(uf_road.members(i)) & set(uf_train.members(i))) for i in range(N)]
print(*ans)

Submission status: Time Limit Exceeded

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())


class UnionFindLabel(UnionFind):
    def __init__(self, labels):
        assert len(labels) == len(set(labels))

        self.n = len(labels)
        self.parents = [-1] * self.n
        self.d = {x: i for i, x in enumerate(labels)}
        self.d_inv = {i: x for i, x in enumerate(labels)}

    def find_label(self, x):
        return self.d_inv[super().find(self.d[x])]

    def union(self, x, y):
        super().union(self.d[x], self.d[y])

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

    def same(self, x, y):
        return super().same(self.d[x], self.d[y])

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

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

def MAP(): return map(int, input().split())
def ZIP(n): return zip(*(MAP() for _ in range(n)))

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

for i in range(K):
    node1, node2 = list(map(int, input().split()))
    uf_road.union(node1 - 1, node2 - 1)

for i in range(L):
    node1, node2 = list(map(int, input().split()))
    uf_train.union(node1 - 1, node2 - 1)

ans = [len(set(uf_road.members(i)) & set(uf_train.members(i))) for i in range(N)]
print(*ans)

Submission status: Time Limit Exceeded

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())


class UnionFindLabel(UnionFind):
    def __init__(self, labels):
        assert len(labels) == len(set(labels))

        self.n = len(labels)
        self.parents = [-1] * self.n
        self.d = {x: i for i, x in enumerate(labels)}
        self.d_inv = {i: x for i, x in enumerate(labels)}

    def find_label(self, x):
        return self.d_inv[super().find(self.d[x])]

    def union(self, x, y):
        super().union(self.d[x], self.d[y])

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

    def same(self, x, y):
        return super().same(self.d[x], self.d[y])

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

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

def MAP(): return map(int, input().split())
def ZIP(n): return zip(*(MAP() for _ in range(n)))

N, K, L = list(map(int, input().split()))
uf_road = UnionFindLabel(range(1, N + 1))
uf_train = UnionFindLabel(range(1, N + 1))

for i in range(K):
    node1, node2 = list(map(int, input().split()))
    uf_road.union(node1, node2)

for i in range(L):
    node1, node2 = list(map(int, input().split()))
    uf_train.union(node1, node2)

ans = [len(set(uf_road.members(i)) & set(uf_train.members(i))) for i in range(1, N + 1)]
print(*ans)