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:
class UnionFind:
    def __init__(self, N):
        self.parent = [x for x in range(N+1)]

    def find(self, x):
        p = x
        while self.parent[p] != p:
            p = self.parent[p]
        self.parent[x] = p
        return p

    def union(self, r, l):
        x, y = self.find(r), self.find(l)
        if x == y:
            return
        self.parent[x] = y

def main():
    N, K, L = map(int, input().split())
    
    rails = UnionFind(N)
    for _ in range(K):
        p, q = map(int, input().split())
        rails.union(p, q)

    loads = UnionFind(N)
    for _ in range(L):
        p, q = map(int, input().split())
        loads.union(p,q)
    RL = [(rails.find(u), loads.find(u)) for u in range(1, N+1)]
    from collections import Counter
    c = Counter(RL)

    print(*(c[x] for x in RL))

main()

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

def main():
  def find(parent, i):
    t = parent[i]
    if t == -1:
      return i
    t = find(parent, t)
    parent[i] = t
    return t

  def unite(parent, i, j):
    i = find(parent, i)
    j = find(parent, j)
    if i == j:
      return
    parent[i] = j

  from builtins import int, map, range
  readline = stdin.readline

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

  roads = [-1] * n
  rails = [-1] * n

  for i in range(k):
    p, q = map(int, readline().split())
    unite(roads, p - 1, q - 1)

  for i in range(l):
    p, q = map(int, readline().split())
    unite(rails, p - 1, q - 1)

  d = {}
  for i in range(n):
    t = (find(roads, i), find(rails, i))
    if t in d:
      d[t] += 1
    else:
      d[t] = 1

  print(*[d[(find(roads, i), find(rails, i))] for i in range(n)])

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stdin
def create_groups(n, links):
  from builtins import len, set
  groups = [-1 for _ in range(n)]
  group_number = 0
  d = deque()
  for i in range(n):
    if groups[i] == -1:
      group_member = []
      d.append(i)
      while len(d) != 0:
        j = d.popleft()
        groups[j] = group_number
        group_member.append(j)
        for k in links[j]:
          if groups[k] == -1:
            d.append(k)
      group_number += 1
  return groups
def read_links(n, k):
  from builtins import int, map
  readline = stdin.readline
  links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, readline().split())
    links[p - 1].append(q - 1)
    links[q - 1].append(p - 1)
  return links
def main():
  from builtins import len
  n, k, l = map(int, input().split())
  road_links = read_links(n, k)
  train_links = read_links(n, l)
  road_groups = create_groups(n, road_links)
  train_groups = create_groups(n, train_links)
  result = {}
  for i in range(n):
    t = (road_groups[i], train_groups[i])
    if t in result:
      result[t] += 1
    else:
      result[t] =1
  print(*[result[(road_groups[i], train_groups[i])] for i in range(n)])
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stdin
def create_groups(n, links):
  from builtins import len, set
  group_set = {}
  groups = [-1 for _ in range(n)]
  group_number = 0
  d = deque()
  for i in range(n):
    if groups[i] == -1:
      group_member = []
      d.append(i)
      while len(d) != 0:
        j = d.popleft()
        groups[j] = group_number
        group_member.append(j)
        for k in links[j]:
          if groups[k] == -1:
            d.append(k)
      group_set[group_number] = set(group_member)
      group_number += 1
  return groups, group_set
def read_links(n, k):
  from builtins import int, map
  readline = stdin.readline
  links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, readline().split())
    links[p - 1].append(q - 1)
    links[q - 1].append(p - 1)
  return links
cache = {}
def intersection_count(i, road_set, road_groups, train_set, train_groups):
  j = road_groups[i]
  k = train_groups[i]
  if (j, k) in cache:
    return cache[(j, k)]
  cache[(j, k)] = len(road_set[j] & train_set[k])
  return cache[(j, k)]
def main():
  from builtins import len
  n, k, l = map(int, input().split())
  road_links = read_links(n, k)
  train_links = read_links(n, l)
  road_groups, road_set = create_groups(n, road_links)
  train_groups, train_set = create_groups(n, train_links)
  print(*[intersection_count(i, road_set, road_groups, train_set, train_groups) for i in range(n)])
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stdin
def create_groups(n, links):
  from builtins import len, set
  group_set = {}
  groups = [-1 for _ in range(n)]
  group_number = 0
  d = deque()
  for i in range(n):
    if groups[i] == -1:
      group_member = []
      d.append(i)
      while len(d) != 0:
        j = d.popleft()
        groups[j] = group_number
        group_member.append(j)
        for k in links[j]:
          if groups[k] == -1:
            d.append(k)
      group_set[group_number] = set(group_member)
      group_number += 1
  return groups, group_set
def read_links(n, k):
  from builtins import int, map
  readline = stdin.readline
  links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, readline().split())
    links[p - 1].append(q - 1)
    links[q - 1].append(p - 1)
  return links
def main():
  from builtins import len
  n, k, l = map(int, input().split())
  road_links = read_links(n, k)
  train_links = read_links(n, l)
  road_groups, road_set = create_groups(n, road_links)
  train_groups, train_set = create_groups(n, train_links)
  print(*[len(road_set[road_groups[i]] & train_set[train_groups[i]]) for i in range(n)])
main()

Submission status: Time Limit Exceeded

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


def Find(x, par):
  if par[x] < 0:
    return x
  else:
    # 経路圧縮
    par[x] = Find(par[x], par)
    return par[x]

def Unite(x, y, par, rank):
  x = Find(x, par)
  y = Find(y, par)
  
  if x != y:
    # rankの低い方を高い方につなげる
    if rank[x] < rank[y]:
      par[y] += par[x]
      par[x] = y
    else:
      par[x] += par[y]
      par[y] = x
      if rank[x] == rank[y]:
        rank[x] += 1
    
def Same(x, y, par):
  return Find(x, par) == Find(y, par)
 
def Size(x, par):
  return -par[Find(x)]

n, k, l = map(int, input().split())
rpar = [-1]* n
tpar = [-1]* n
rrank = [0]*n
trank = [0]*n

for i in range(k):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, rpar, rrank) 

for i_ in range(l):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, tpar, trank)

d = {}
IDs = [0]*n
for j in range(n):
  ID = Find(j, rpar)+(Find(j, tpar)+1)*10**8
  IDs[j] = ID
  if ID in d:
    d[ID] += 1
  else:
    d[ID] = 1

ans = ''
for j_ in range(n):
  if j_ != 0:
    ans += ' '
  ans += str(d[IDs[j_]])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stdin
def f(n, links, groups):
  group_number = 0
  for i in range(n):
    if groups[i] == -1:
      d = deque()
      d.append(i)
      while len(d) != 0:
        j = d.popleft()
        groups[j] = group_number
        for k in links[j]:
          if groups[k] == -1:
            d.append(k)
      group_number += 1
  d = {}
  for i in range(n):
    if groups[i] not in d:
      d[groups[i]] = []
    d[groups[i]].append(i)
  for k in d:
    d[k] = set(d[k])
  return d
def main():
  # from builtins import int, list, map, min
  readline = stdin.readline
  n, k, l = map(int, input().split())
  road_links = [[] for _ in range(n)]
  for i in range(k):
    p, q = map(int, readline().split())
    road_links[p - 1].append(q - 1)
    road_links[q - 1].append(p - 1)
  road_groups = [-1 for _ in range(n)]
  road_set = f(n, road_links, road_groups)
  train_links = [[] for _ in range(n)]
  for i in range(l):
    p, q = map(int, readline().split())
    train_links[p - 1].append(q - 1)
    train_links[q - 1].append(p - 1)
  train_groups = [-1 for _ in range(n)]
  train_set = f(n, train_links, train_groups)
  print(*[len(road_set[road_groups[i]] & train_set[train_groups[i]]) for i in range(n)])
main()

Submission status: Time Limit Exceeded

Solution code:
def Find(x, par):
  if par[x] < 0:
    return x
  else:
    # 経路圧縮
    par[x] = Find(par[x], par)
    return par[x]

def Unite(x, y, par, rank):
  x = Find(x, par)
  y = Find(y, par)
  
  if x != y:
    # rankの低い方を高い方につなげる
    if rank[x] < rank[y]:
      par[y] += par[x]
      par[x] = y
    else:
      par[x] += par[y]
      par[y] = x
      if rank[x] == rank[y]:
        rank[x] += 1
    
def Same(x, y, par):
  return Find(x, par) == Find(y, par)
 
def Size(x, par):
  return -par[Find(x)]

n, k, l = map(int, input().split())
rpar = [-1]* n
tpar = [-1]* n
rrank = [0]*n
trank = [0]*n

for i in range(k):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, rpar, rrank) 

for i_ in range(l):
  p, q = map(int, input().split())
  p, q =p-1, q-1
  Unite(p,q, tpar, trank)

d = {}
IDs = [0]*n
for j in range(n):
  ID = Find(j, rpar)+(Find(j, tpar)+1)*10**8
  IDs[j] = ID
  if ID in d:
    d[ID] += 1
  else:
    d[ID] = 1

ans = ''
for j_ in range(n):
  if j_ != 0:
    ans += ' '
  ans += str(d[IDs[j_]])
print(ans)

Submission status: Time Limit Exceeded

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

class UnionFind():
  def __init__(self, n):
    self.n = n
    # n+1なのはノード番号とリストのインデックスを一致させるため
    # root[x]<0ならそのノードが根かつその絶対値が木の要素数
    self.root = [-1]*(n+1)
    self.rnk = [0]*(n+1)
  
  def Find_Root(self, x):
    if self.root[x] < 0:
      return x
    else:
      self.root[x] = self.Find_Root(self.root[x])
      return self.root[x]
    
  def Unite(self, x, y):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if x == y:
      return
    elif(self.rnk[x] > self.rnk[y]):
      self.root[x] += self.root[y]
      self.root[y] = x
    else:
      self.root[y] += self.root[x]
      self.root[x] = y
      if self.rnk[x] == self.rnk[y]:
        self.rnk[y] += 1
 
  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
  
  def Count(self, x):
    return -self.root[self.Find_Root(x)]
  
n, k, l = map(int, input().split())
UFd= UnionFind(n)
UFt= UnionFind(n)

for i in range(k):
  p, q = map(int, input().split())
  UFd.Unite(p, q)

for j in range(l):
  p, q = map(int, input().split())
  UFt.Unite(p, q)
  
ids = [0]*n
d = {}
for i in range(n):
  if UFd.root[i+1] < 0:
    idd = i+1
  else:
    idd = UFd.root[i+1]
  if UFt.root[i+1] < 0:
    idt = i+1
  else:
    idt = UFt.root[i+1]
  iddt = idd*10**6+idt
  ids[i] = iddt
  if iddt in d:
    d[iddt] += 1
  else:
    d[iddt] = 1
ans = ''
for i in range(n):
  if i != 0:
    ans += ' '
  ans += str(d[ids[i]])
print(ans)

Submission status: Time Limit Exceeded

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

class UnionFind():
  def __init__(self, n):
    self.n = n
    # n+1なのはノード番号とリストのインデックスを一致させるため
    # root[x]<0ならそのノードが根かつその絶対値が木の要素数
    self.root = [-1]*(n+1)
    self.rnk = [0]*(n+1)
  
  def Find_Root(self, x):
    if self.root[x] < 0:
      return x
    else:
      self.root[x] = self.Find_Root(self.root[x])
      return self.root[x]
    
  def Unite(self, x, y):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if x == y:
      return
    elif(self.rnk[x] > self.rnk[y]):
      self.root[x] += self.root[y]
      self.root[y] = x
    else:
      self.root[y] += self.root[x]
      self.root[x] = y
      if self.rnk[x] == self.rnk[y]:
        self.rnk[y] += 1
 
  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
  
  def Count(self, x):
    return -self.root[self.Find_Root(x)]
  
n, k, l = map(int, input().split())
UFd= UnionFind(n)
UFt= UnionFind(n)

for i in range(k):
  p, q = map(int, input().split())
  UFd.Unite(p, q)

for j in range(l):
  p, q = map(int, input().split())
  UFt.Unite(p, q)
  
ids = [0]*n
d = {}
for i in range(n):
  if UFd.root[i+1] > 0:
    idd = UFd.root[i+1]
  else:
    idd = i+1
  if UFt.root[i+1] > 0:
    idt = UFt.root[i+1]
  else:
    idt = i+1
  iddt = idd*10**6+idt
  ids[i] = iddt
  if iddt in d:
    d[iddt] += 1
  else:
    d[iddt] = 1
ans = ''
for i in range(n):
  if i != 0:
    ans += ' '
  ans += str(d[ids[i]])
print(ans)

Submission status: Time Limit Exceeded

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

class UnionFind():
  def __init__(self, n):
    self.n = n
    # n+1なのはノード番号とリストのインデックスを一致させるため
    # root[x]<0ならそのノードが根かつその絶対値が木の要素数
    self.root = [-1]*(n+1)
    self.rnk = [0]*(n+1)
  
  def Find_Root(self, x):
    if self.root[x] < 0:
      return x
    else:
      self.root[x] = self.Find_Root(self.root[x])
      return self.root[x]
    
  def Unite(self, x, y):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if x == y:
      return
    elif(self.rnk[x] > self.rnk[y]):
      self.root[x] += self.root[y]
      self.root[y] = x
    else:
      self.root[y] += self.root[x]
      self.root[x] = y
      if self.rnk[x] == self.rnk[y]:
        self.rnk[y] += 1
 
  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
  
  def Count(self, x):
    return -self.root[self.Find_Root(x)]
  
n, k, l = map(int, input().split())
UFd= UnionFind(n)
UFt= UnionFind(n)

for i in range(k):
  p, q = map(int, input().split())
  UFd.Unite(p, q)

for j in range(l):
  p, q = map(int, input().split())
  UFt.Unite(p, q)
  
ids = []
d = {}
for i in range(n):
  if UFd.root[i+1] > 0:
    idd = UFd.root[i+1]
  else:
    idd = i+1
  if UFt.root[i+1] > 0:
    idt = UFt.root[i+1]
  else:
    idt = i+1
  iddt = idd*10**6+idt
  ids.append(iddt)
  if iddt in d:
    d[iddt] += 1
  else:
    d[iddt] = 1
ans = ''
for i in range(n):
  if i != 0:
    ans += ' '
  ans += str(d[ids[i]])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
class UnionFind():
  def __init__(self, n):
    self.n = n
    # n+1なのはノード番号とリストのインデックスを一致させるため
    # root[x]<0ならそのノードが根かつその絶対値が木の要素数
    self.root = [-1]*(n+1)
    self.rnk = [0]*(n+1)
  
  def Find_Root(self, x):
    if self.root[x] < 0:
      return x
    else:
      self.root[x] = self.Find_Root(self.root[x])
      return self.root[x]
    
  def Unite(self, x, y):
    x = self.Find_Root(x)
    y = self.Find_Root(y)
    if x == y:
      return
    elif(self.rnk[x] > self.rnk[y]):
      self.root[x] += self.root[y]
      self.root[y] = x
    else:
      self.root[y] += self.root[x]
      self.root[x] = y
      if self.rnk[x] == self.rnk[y]:
        self.rnk[y] += 1
 
  def isSameGroup(self, x, y):
    return self.Find_Root(x) == self.Find_Root(y)
  
  def Count(self, x):
    return -self.root[self.Find_Root(x)]
  
n, k, l = map(int, input().split())
UFd= UnionFind(n)
UFt= UnionFind(n)

for i in range(k):
  p, q = map(int, input().split())
  UFd.Unite(p, q)

for j in range(l):
  p, q = map(int, input().split())
  UFt.Unite(p, q)
  
ids = []
d = {}
for i in range(n):
  if UFd.root[i+1] > 0:
    idd = UFd.root[i+1]
  else:
    idd = i+1
  if UFt.root[i+1] > 0:
    idt = UFt.root[i+1]
  else:
    idt = i+1
  iddt = idd*10**6+idt
  ids.append(iddt)
  if iddt in d:
    d[iddt] += 1
  else:
    d[iddt] = 1
ans = ''
for i in range(n):
  if i != 0:
    ans += ' '
  ans += str(d[ids[i]])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
def find_root(edges, edges_root, root, searched, before, now):
    searched[now] = True
    edges_root[now] = root
    children = set(edges[now])
    for child in children:
        if child != before and not searched[child]:
            root, edges_root, searched = find_root(edges, edges_root, root, searched, now, child)
    return root, edges_root, searched
    
if __name__ == '__main__':
    N, K, L = map(int, input().split())
    roads = [[] for _ in range(N)]
    rails = [[] for _ in range(N)]
    road_roots = [None]*N
    rail_roots = [None]*N
    answer = [1]*N
        
    for i in range(K):
        p, q = map(int, input().split())
        p -= 1
        q -= 1
        roads[p].append(q)
        roads[q].append(p)
    
    for i in range(L):
        r, s = map(int, input().split())
        r -= 1
        s -= 1
        rails[r].append(s)
        rails[s].append(r)
    
    for i, r in enumerate(road_roots):
        if r is None:
            root, road_roots, group = find_root(roads,road_roots, i, [False]*N, -1, i)


    for i, r in enumerate(rail_roots):
        if r is None:
            root, rail_roots, group = find_root(rails,rail_roots, i, [False]*N, -1, i)

                
    railroads=[[rail, road] for rail, road in zip(road_roots, rail_roots)]

    for n in range(N):
        for d in range(1, N-n):
            if railroads[n] == railroads[n+d]:
                answer[n] += 1 
                answer[n+d] += 1
                
    print(' '.join(list(map(str, answer))))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
def find_root(edges, edges_root, root, group, before, now):
    group.add(now)
    edges_root[now] = root
    children = set(edges[now]) - group
    for child in children:
        if child != before:
            root, edges_root, group = find_root(edges, edges_root, root, group, now, child)
    return root, edges_root, group
    
if __name__ == '__main__':
    N, K, L = map(int, input().split())
    roads = [[] for _ in range(N)]
    rails = [[] for _ in range(N)]
    road_roots = [None]*N
    rail_roots = [None]*N
    answer = [1]*N
        
    for i in range(K):
        p, q = map(int, input().split())
        p -= 1
        q -= 1
        roads[p].append(q)
        roads[q].append(p)
    
    for i in range(L):
        r, s = map(int, input().split())
        r -= 1
        s -= 1
        rails[r].append(s)
        rails[s].append(r)
    
    for i, r in enumerate(road_roots):
        if r is None:
            root, road_roots, group = find_root(roads,road_roots, i, set(), -1, i)


    for i, r in enumerate(rail_roots):
        if r is None:
            root, rail_roots, group = find_root(rails,rail_roots, i, set(), -1, i)

                
    railroads=[[rail, road] for rail, road in zip(road_roots, rail_roots)]

    for n in range(N):
        for d in range(1, N-n):
            if railroads[n] == railroads[n+d]:
                answer[n] += 1 
                answer[n+d] += 1
                
    print(' '.join(list(map(str, answer))))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
def find_root(edges, edges_root, root, group, before, now):
    group.append(now)
    edges_root[now] = root
    children = edges[now]
    for child in children:
        if child != before and child not in group:
            root, edges_root, group = find_root(edges, edges_root, root, group, now, child)
    return root, edges_root, group
    
if __name__ == '__main__':
    N, K, L = map(int, input().split())
    roads = [[] for _ in range(N)]
    rails = [[] for _ in range(N)]
    road_roots = [None]*N
    rail_roots = [None]*N
    answer = [1]*N
        
    for i in range(K):
        p, q = map(int, input().split())
        p -= 1
        q -= 1
        roads[p].append(q)
        roads[q].append(p)
    
    for i in range(L):
        r, s = map(int, input().split())
        r -= 1
        s -= 1
        rails[r].append(s)
        rails[s].append(r)
    
    for i, r in enumerate(road_roots):
        if r is None:
            root, road_roots, group = find_root(roads,road_roots, i, [], -1, i)


    for i, r in enumerate(rail_roots):
        if r is None:
            root, rail_roots, group = find_root(rails,rail_roots, i, [], -1, i)

                
    railroads=[[rail, road] for rail, road in zip(road_roots, rail_roots)]

    for n in range(N):
        for d in range(1, N-n):
            if railroads[n] == railroads[n+d]:
                answer[n] += 1 
                answer[n+d] += 1
                
    print(' '.join(list(map(str, answer))))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
def find_root(edges, root, group, before, now):
    group.append(now)
    children = edges[now]
    for child in children:
        if child != before and child not in group:
            root, group = find_root(edges, root, group, now, child)
    return root, group
    
if __name__ == '__main__':
    N, K, L = map(int, input().split())
    roads = [[] for _ in range(N)]
    rails = [[] for _ in range(N)]
    road_roots = [None]*N
    rail_roots = [None]*N
    answer = [1]*N
        
    for i in range(K):
        p, q = map(int, input().split())
        p -= 1
        q -= 1
        roads[p].append(q)
        roads[q].append(p)
    
    for i in range(L):
        r, s = map(int, input().split())
        r -= 1
        s -= 1
        rails[r].append(s)
        rails[s].append(r)
    
    for i, r in enumerate(road_roots):
        if r is None:
            root, group = find_root(roads, i, [], -1, i)
            for g in group:
                road_roots[g] = root

    for i, r in enumerate(rail_roots):
        if r is None:
            root, group = find_root(rails, i, [], -1, i)
            for g in group:
                rail_roots[g] = root
                
    railroads=[[rail, road] for rail, road in zip(road_roots, rail_roots)]

    for n in range(N):
        for d in range(1, N-n):
            if railroads[n] == railroads[n+d]:
                answer[n] += 1 
                answer[n+d] += 1
                
    print(' '.join(list(map(str, answer))))

Submission status: Time Limit Exceeded

Solution code:
from collections import*
n,k,l=map(int,input().split());d=[-1]*n;t=[-1]*n;M=lambda:map(int,input().split())
def f(l,x):
  if l[x]<0:return x
  else:l[x]=f(l,l[x]);return l[x]
def u(l,x,y):
  if f(l,x)!=f(l,y):l[f(l,y)]=f(l,x)
for _ in range(k):a,b=M();u(d,a-1,b-1)
for _ in range(l):a,b=M();u(t,a-1,b-1)
p=[(f(d,i),f(t,i))for i in range(n)];print(*[Counter(p)[p[i]]for i in range(n)])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC54 D

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7

n,k,l = map(int,input().split())
par1 = [i for i in range(n)]
par2 = [i for i in range(n)]

rank1 = [0]*(n)
rank2 = [0]*(n)

def find(x,i):
    if i == 1:
        if par1[x] == x:
            return x
        else:
            par1[x] = find(par1[x],i)
            return par1[x]
    else:
        if par2[x] == x:
            return x
        else:
            par2[x] = find(par2[x],i)
            return par2[x]

def check(x,y,i):
    return find(x,i) == find(y,i)

def union(x,y,i):
    x = find(x,i)
    y = find(y,i)
    if i == 1:
        if rank1[x] < rank1[y]:
            par1[x] = y
        else:
            par1[y] = x
            if rank1[x] == rank1[y]:
                rank1[x] += 1
    else:
        if rank2[x] < rank2[y]:
            par2[x] = y
        else:
            par2[y] = x
            if rank2[x] == rank2[y]:
                rank2[x] += 1

for _ in range(k):
    p,q = map(int,input().split())
    union(p-1,q-1,1)
for _ in range(l):
    r,s = map(int,input().split())
    union(r-1,s-1,2)

ans = []
for i in range(n):
    cnt = 1
    for j in range(n):
        if i == j:
            continue
        if check(i,j,1) and check(i,j,2):
            cnt += 1
    ans.append(cnt)
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)
def input():
  return sys.stdin.readline()[:-1]

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

#################

N,K,L = II()
p,q = Line(K)
r,s = Line(L)

class UF(object):
  def __init__(self, n=1):
    self.par = [i for i in range(n)]
    self.rank = [0 for _ in range(n)]
    self.size = [1 for _ in range(n)]

  def find(self, x):
    """
    x が属するグループを探索
    """
    if self.par[x] == x:
      return x
    else:
      self.par[x] = self.find(self.par[x])
      return self.par[x]

  def union(self, x, y):
    """
    x と y のグループを結合
    """
    x = self.find(x)
    y = self.find(y)
    if x != y:
      if self.rank[x] < self.rank[y]:
        x, y = y, x
      if self.rank[x] == self.rank[y]:
        self.rank[x] += 1
      self.par[y] = x
      self.size[x] += self.size[y]

  def is_same(self, x, y):
    """
    x と y が同じグループか否か
    """
    return self.find(x) == self.find(y)

  def get_size(self, x):
    """
    x が属するグループの要素数
    """
    x = self.find(x)
    return self.size[x]
  
uf1 = UF(N)
uf2 = UF(N)
ans = []

for i in range(K):
  uf1.union(p[i]-1,q[i]-1)

for i in range(L):
  uf2.union(r[i]-1,s[i]-1)

x = defaultdict(set)
xroot = [0]*N
y = defaultdict(set)
yroot = [0]*N
for i in range(N):
  xroot[i] = uf1.find(i)
  x[xroot[i]].add(i)
  yroot[i] = uf2.find(i)
  y[yroot[i]].add(i)

for i in range(N):
  ans.append(len(set(x[xroot[i]]) & set(y[yroot[i]])))

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)
def input():
  return sys.stdin.readline()[:-1]

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

#################

N,K,L = II()
p,q = Line(K)
r,s = Line(L)

class UF(object):
  def __init__(self, n=1):
    self.par = [i for i in range(n)]
    self.rank = [0 for _ in range(n)]
    self.size = [1 for _ in range(n)]

  def find(self, x):
    """
    x が属するグループを探索
    """
    if self.par[x] == x:
      return x
    else:
      self.par[x] = self.find(self.par[x])
      return self.par[x]

  def union(self, x, y):
    """
    x と y のグループを結合
    """
    x = self.find(x)
    y = self.find(y)
    if x != y:
      if self.rank[x] < self.rank[y]:
        x, y = y, x
      if self.rank[x] == self.rank[y]:
        self.rank[x] += 1
      self.par[y] = x
      self.size[x] += self.size[y]

  def is_same(self, x, y):
    """
    x と y が同じグループか否か
    """
    return self.find(x) == self.find(y)

  def get_size(self, x):
    """
    x が属するグループの要素数
    """
    x = self.find(x)
    return self.size[x]
  
uf1 = UF(N)
uf2 = UF(N)
ans = []

for i in range(K):
  uf1.union(p[i]-1,q[i]-1)

for i in range(L):
  uf2.union(r[i]-1,s[i]-1)

x = defaultdict(set)
y = defaultdict(set)
for i in range(N):
  x[uf1.find(i)].add(i)
  y[uf2.find(i)].add(i)

for i in range(N):
  ans.append(len(set(x[uf1.find(i)]) & set(y[uf2.find(i)])))

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.children = []
        self.size = 1
    
class UF:
    def __init__(self, size):
        self.n = size
        self.parents = [i for i in range(self.n+1)]
        self.sizes = [1] * (self.n+1)
        self.nodes = [None]
        for i in range(1, self.n+1):
            self.nodes.append(Node(i))
        

    def get_parent(self, x):
        while x.parent != None:
            x = x.parent
        return x

    def union(self, x, y):
        x = self.nodes[x]
        y = self.nodes[y]
        xp = self.get_parent(x)
        yp = self.get_parent(y)
        if xp == yp and xp is not None and yp is not None:
            return
        if xp.size >= yp.size:
            xp.children.append(yp)
            xp.size += yp.size
            self.sink(xp, yp)
        else:
            yp.children.append(xp)
            yp.size += xp.size
            self.sink(yp, xp)

    def sink(self, xp, yp):
        yp.parent = xp
        self.parents[yp.key] = xp.key
        yp.size = xp.size
        for child in yp.children:
            self.sink(xp, child)
            
from collections import defaultdict
n, k, l = map(int, raw_input().split())
uf1 = UF(n)
for i in range(k):
    p, q = map(int, raw_input().split())
    uf1.union(p, q)
uf2 = UF(n)
for i in range(l):
    r, s = map(int, raw_input().split())
    uf2.union(r, s)
p1 = uf1.parents
p2 = uf2.parents
dic = defaultdict(int)
for i in range(1, n+1):
    key = (p1[i], p2[i])
    dic[key] += 1
res_arr = []
for i in range(1, n+1):
    if uf1.nodes[i].size == 1 or uf2.nodes[i].size == 1:
        res_arr.append(1)
    else:
        key = (p1[i], p2[i])
        res_arr.append(dic[key])
print " ".join(map(str, res_arr))

Submission status: Time Limit Exceeded

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

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

vec1, vec2 = [[] for _ in range(N)], [[] for _ in range(N)]

for _ in range(K) :
    p, q = map(int, input().split())
    vec1[p-1].append(q-1)
    vec1[q-1].append(p-1)
for _ in range(L) :
    r, s = map(int, input().split())
    vec2[r-1].append(s-1)
    vec2[s-1].append(r-1)

def bfs(v) :
    visited = [-1] * N
    ret = []
    n = 0
    for i in range(N) :
        if visited[i] < 0 :
            queue = [i]
            visited[i] = n
            j = 0
            while j < len(queue) :
                cur = queue[j]
                for nex in v[cur] :
                    if visited[nex] < 0 :
                        queue.append(nex)
                        visited[nex] = n
                j += 1
                
            ret.append(set(queue))
            n += 1
            
    return ret, visited
    
ret1, visited1 = bfs(vec1)
ret2, visited2 = bfs(vec2)
ret = [str(len(ret1[visited1[i]] & ret2[visited2[i]])) for i in range(N)]

print(' '.join(ret))