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:
#!/usr/bin/env python3

from sys import stdin, setrecursionlimit


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

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        p = self.parent
        if x != y:
            if x > y:
                x, y = y, x
            p[x], p[y] = p[x] + p[y], x

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

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


def main():
    input = stdin.buffer.readline
    n, k, l = map(int, input().split())

    fk = UnionFindTree(n)
    for _ in range(k):
        p, q = map(int, input().split())
        fk.union(p - 1, q - 1)

    fl = UnionFindTree(n)
    for _ in range(l):
        r, s = map(int, input().split())
        fl.union(r - 1, s - 1)

    ans = []
    for i in range(n):
        tmp = 0
        for j in range(n):
            if fk.same(i, j) and fl.same(i, j):
                tmp += 1
        ans.append(tmp)

    print(*ans)


if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

Submission status: Time Limit Exceeded

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

from sys import stdin, setrecursionlimit
from collections import deque


def main():
    input = stdin.buffer.readline
    n, k, l = map(int, input().split())

    gk = [[] for _ in range(n)]
    for _ in range(k):
        p, q = map(int, input().split())
        gk[p - 1].append(q - 1)
        gk[q - 1].append(p - 1)

    gl = [[] for _ in range(n)]
    for _ in range(l):
        r, s = map(int, input().split())
        gl[r - 1].append(s - 1)
        gl[s - 1].append(r - 1)

    ans = []

    for i in range(n):
        qk = deque([i])
        seen_k = [False] * n
        seen_k[i] = True

        while qk:
            u = qk.popleft()

            for v in gk[u]:
                if not seen_k[v]:
                    seen_k[v] = True
                    qk.append(v)

        ql = deque([i])
        seen_l = [False] * n
        seen_l[i] = True

        while ql:
            u = ql.popleft()

            for v in gl[u]:
                if not seen_l[v]:
                    seen_l[v] = True
                    ql.append(v)

        tmp = 0

        for sk, sl in zip(seen_k, seen_l):
            if sk and sl:
                tmp += 1

        ans.append(tmp)

    print(*ans)


if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

Submission status: Time Limit Exceeded

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

class UnionFind():
    def __init__(self, n):
        # size of n.
        self.n = n
        # n's parent. default is -1.
        self.parents = [-1] * n

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

    def union_merge(self, x, y):
        x = self.find_root(x)
        y = self.find_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 union_size(self, x):
        # Root value's index has its size with negative.
        return -self.parents[self.find_root(x)]

    def is_same_union(self, x, y):
        return self.find_root(x) == self.find_root(y)

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

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

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

    def all_unions(self):
        return [self.same_union_members(r) for r in self.roots()]

road = UnionFind(N)
rail = UnionFind(N)

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

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

result = []
for i in range(N):
    road_members = road.same_union_members(i)
    rail_members = rail.same_union_members(i)
    road_rail_both_members = set(road_members).intersection(set(rail_members))
    result.append(len(road_rail_both_members))

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

Submission status: Time Limit Exceeded

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

class UnionFind():
    def __init__(self, n):
        # size of n.
        self.n = n
        # n's parent. default is -1.
        self.parents = [-1] * n

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

    def union_merge(self, x, y):
        x = self.find_root(x)
        y = self.find_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 union_size(self, x):
        # Root value's index has its size with negative.
        return -self.parents[self.find_root(x)]

    def is_same_union(self, x, y):
        return self.find_root(x) == self.find_root(y)

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

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

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

    def all_unions(self):
        return [self.same_union_members(r) for r in self.roots()]

road = UnionFind(N)
rail = UnionFind(N)

for i in range(K):
    p, k = map(int, input().split())
    p -= 1
    k -= 1
    if not road.is_same_union(p, k):
        road.union_merge(p, k)

for i in range(L):
    r, s = map(int, input().split())
    r -= 1
    s -= 1
    if not rail.is_same_union(r, s):
        rail.union_merge(r, s)

result = []
for i in range(N):
    road_members = road.same_union_members(i)
    rail_members = rail.same_union_members(i)
    road_rail_both_members = set(road_members).intersection(set(rail_members))
    result.append(len(road_rail_both_members))

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

Submission status: Time Limit Exceeded

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

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)
    u=0
    s=deque()
    stack=deque()
    while es:
        f=es.pop()
        stack.clear()
        while True:
            l=len(es)
            while es:
                g=es.pop()
                if g&f:
                    f|=g
                else:
                    stack.append(g)
            es=deepcopy(stack)
            if l==len(stack):
                s.append(f)
                u+=len(f)
                break
    t=[x for x in range(u,u+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: Time Limit Exceeded

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

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)
    s=deque()
    stack=deque()
    while es:
        f=es.pop()
        stack.clear()
        while True:
            l=len(es)
            while es:
                g=es.pop()
                if g&f:
                    f|=g
                else:
                    stack.append(g)
            es=deepcopy(stack)
            if l==len(stack):
                s.append(f)
                break
    t=[x for x in range(n*(n-1),n*(n-1)+n)]
    c=1
    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: Time Limit Exceeded

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)
        else:
            td[da].extend(td[db])
            for x in td[db]:
                d[x]=da

    return list(d.values())

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = 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 main():
    N, K, L = map(int, readline().rstrip().split())
    uf1 = UnionFind(N)
    uf2 = UnionFind(N)
    
    for _ in range(K):
        p, q = map(int, readline().rstrip().split())
        uf1.union(p-1, q-1)
    
    for _ in range(L):
        r, s = map(int, readline().rstrip().split())
        uf2.union(r-1, s-1)
    
    res = []
    road = uf1.all_group_members()
    train = uf2.all_group_members()

    for i in range(N):
        res.append(len(set(road[uf1.find(i)]) & set(train[uf2.find(i)])))
    
    print(*res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = 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 main():
    N, K, L = map(int, readline().rstrip().split())
    uf1 = UnionFind(N)
    uf2 = UnionFind(N)
    
    for _ in range(K):
        p, q = map(int, readline().rstrip().split())
        uf1.union(p-1, q-1)
    
    for _ in range(L):
        r, s = map(int, readline().rstrip().split())
        uf2.union(r-1, s-1)
    
    res = []
    road = [-1] * N
    train = [-1] * N

    for i in range(N):
        if road[i] == -1:
            roads = set(uf1.members(i))
            roads.add(i)
            for r in roads:
                road[r] = roads
        if train[i] == -1:
            trains = set(uf2.members(i))
            trains.add(i)
            for t in trains:
                train[t] = trains
            
        res.append(len(road[i] & train[i]))
    
    print(*res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = 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 main():
    N, K, L = map(int, readline().rstrip().split())
    uf1 = UnionFind(N)
    uf2 = UnionFind(N)
    
    for _ in range(K):
        p, q = map(int, readline().rstrip().split())
        uf1.union(p-1, q-1)
    
    for _ in range(L):
        r, s = map(int, readline().rstrip().split())
        uf2.union(r-1, s-1)
    
    res = []
    road = [-1] * N
    train = [-1] * N

    for i in range(N):
        if road[i] == -1:
            roads = set(uf1.members(i))
            roads.add(i)
            for r in roads:
                road[r] = roads
        if train[i] == -1:
            trains = set(uf2.members(i))
            trains.add(i)
            for t in trains:
                train[t] = trains
            
        res.append(len(road[i] & train[i]))
    
    print(*res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = 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 main():
    N, K, L = map(int, readline().rstrip().split())
    uf1 = UnionFind(N)
    uf2 = UnionFind(N)
    
    for _ in range(K):
        p, q = map(int, readline().rstrip().split())
        uf1.union(p-1, q-1)
    
    for _ in range(L):
        r, s = map(int, readline().rstrip().split())
        uf2.union(r-1, s-1)
    
    res = []
    for i in range(N):
        res.append(len(set(uf1.members(i)) & set(uf2.members(i))))
    
    print(*res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,k,l=map(int,input().split())
load=[[] for _ in range(n)]
train=[[] for _ in range(n)]
for _ in range(k):
  a,b=map(int,input().split())
  a-=1
  b-=1
  load[a].append(b)
  load[b].append(a)
for _ in range(l):
  a,b=map(int,input().split())
  a-=1
  b-=1
  train[a].append(b)
  train[b].append(a)

# 道路の連結グループ
load_grp_id=[-1]*n
for t0 in range(n):
  if load_grp_id[t0]!=-1:continue
  todo=[t0]
  seen=[0]*n
  load_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    l=load[t]
    for li in l:
      if load_grp_id[li]==-1:
        load_grp_id[li]=t0
        todo.append(li)
# 鉄道の連結グループ
train_grp_id=[-1]*n
for t0 in range(n):
  if train_grp_id[t0]!=-1:continue
  todo=[t0]
  seen=[0]*n
  train_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    l=train[t]
    for li in l:
      if train_grp_id[li]==-1:
        train_grp_id[li]=t0
        todo.append(li)

d={}
for i in range(n):
  lid=load_grp_id[i]
  tid=train_grp_id[i]
  if (lid,tid) in d:
    d[(lid,tid)]+=1
  else:
    d[(lid,tid)]=1
ans=[]
for i in range(n):
  lid=load_grp_id[i]
  tid=train_grp_id[i]
  ans.append(str(d[(lid,tid)]))
print(' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
n,k,l=map(int,input().split())
load=[[] for _ in range(n)]
train=[[] for _ in range(n)]
for _ in range(k):
  a,b=map(int,input().split())
  a-=1
  b-=1
  load[a].append(b)
  load[b].append(a)
for _ in range(l):
  a,b=map(int,input().split())
  a-=1
  b-=1
  train[a].append(b)
  train[b].append(a)
# 道路の連結グループ
not_seen=set(range(n))
load_grp={}
load_grp_id=[-1]*n
while not_seen:
  t0=list(not_seen)[0]
  todo=[t0]
  seen=[0]*n
  load_grp[t0]=set([t0])
  load_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    not_seen.discard(t)
    l=load[t]
    for li in l:
      if load_grp_id[li]==-1:
        load_grp[t0].add(li)
        load_grp_id[li]=t0
        todo.append(li)
# 鉄道の連結グループ
not_seen=set(range(n))
train_grp={}
train_grp_id=[-1]*n
while not_seen:
  t0=list(not_seen)[0]
  todo=[t0]
  seen=[0]*n
  train_grp[t0]=set([t0])
  train_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    not_seen.discard(t)
    l=train[t]
    for li in l:
      if train_grp_id[li]==-1:
        train_grp[t0].add(li)
        train_grp_id[li]=t0
        todo.append(li)
from collections import defaultdict
d=defaultdict(int)
for i in range(n):
  lid=load_grp_id[i]
  tid=train_grp_id[i]
  d[(lid,tid)]+=1
ans=[]
for i in range(n):
  lid=load_grp_id[i]
  tid=train_grp_id[i]
  ans.append(str(d[(lid,tid)]))
print(' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
n,k,l=map(int,input().split())
load=[[] for _ in range(n)]
train=[[] for _ in range(n)]
for _ in range(k):
  a,b=map(int,input().split())
  a-=1
  b-=1
  load[a].append(b)
  load[b].append(a)
for _ in range(l):
  a,b=map(int,input().split())
  a-=1
  b-=1
  train[a].append(b)
  train[b].append(a)
# 道路の連結グループ
not_seen=set(range(n))
load_grp={}
load_grp_id=[-1]*n
while not_seen:
  t0=list(not_seen)[0]
  todo=[t0]
  seen=[0]*n
  load_grp[t0]=set([t0])
  load_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    not_seen.discard(t)
    l=load[t]
    for li in l:
      if load_grp_id[li]==-1:
        load_grp[t0].add(li)
        load_grp_id[li]=t0
        todo.append(li)
# 鉄道の連結グループ
not_seen=set(range(n))
train_grp={}
train_grp_id=[-1]*n
while not_seen:
  t0=list(not_seen)[0]
  todo=[t0]
  seen=[0]*n
  train_grp[t0]=set([t0])
  train_grp_id[t0]=t0
  while todo:
    t=todo.pop()
    not_seen.discard(t)
    l=train[t]
    for li in l:
      if train_grp_id[li]==-1:
        train_grp[t0].add(li)
        train_grp_id[li]=t0
        todo.append(li)

ans=[]
for i in range(n):
  lg=load_grp[load_grp_id[i]]
  tg=train_grp[train_grp_id[i]]
  ans.append(str(len(lg.intersection(tg))))
print(' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
import copy
N,K,L = map(int,input().split())
dctK = {}
dctL = {}
for n in range(1,N + 1):
    dctK[n] = {n:0}
    dctL[n] = {n:0}
for k in range(K):
    p,q = map(int,input().split())
    dctK[p][q] = 0
    dctK[q][p] = 0
for l in range(L):
    r,s = map(int,input().split())
    dctL[r][s] = 0
    dctL[s][r] = 0
for k1 in dctK:
    dctK1 = dctK[k1]
    k2 = copy.copy(dctK1)
    while len(k2) > 0:
        dctAdd = {}
        for k3 in k2:
            for k4 in dctK[k3]:
                if k4 in dctK1:
                    continue
                dctAdd[k4] = 0
                dctK1[k4] = 0
                dctK[k4][k3] = 0
        k2 = dctAdd
for l1 in dctL:
    dctL1 = dctL[l1]
    l2 = copy.copy(dctL1)
    while len(l2) > 0:
        dctAdd = {}
        for l3 in l2:
            for l4 in dctL[l3]:
                if l4 in dctL1:
                    continue
                dctAdd[l4] = 0
                dctL1[l4] = 0
                dctL[l4][l3] = 0
        l2 = dctAdd
lstCnt = []
for n in range(1,n + 1):
    cnt = 0
    for k in dctK[n]:
        if k in dctL[n]:
            cnt += 1
    lstCnt.append(cnt)
m = map(str,lstCnt)
print(" ".join(m))

Submission status: Time Limit Exceeded

Solution code:
import copy
N,K,L = map(int,input().split())
dctK = {}
dctL = {}
for n in range(1,N + 1):
    dctK[n] = {n:0}
    dctL[n] = {n:0}
for k in range(K):
    p,q = map(int,input().split())
    dctK[p][q] = 0
    dctK[q][p] = 0
for l in range(L):
    r,s = map(int,input().split())
    dctL[r][s] = 0
    dctL[s][r] = 0
for k1 in dctK:
    dctK1 = dctK[k1]
    k2 = copy.copy(dctK1)
    while len(k2) > 0:
        dctAdd = {}
        for k3 in k2:
            for k4 in dctK[k3]:
                if k4 in dctK1:
                    continue
                dctAdd[k4] = 0
                dctK1[k4] = 0
        k2 = dctAdd
for l1 in dctL:
    dctL1 = dctL[l1]
    l2 = copy.copy(dctL1)
    while len(l2) > 0:
        dctAdd = {}
        for l3 in l2:
            for l4 in dctL[l3]:
                if l4 in dctL1:
                    continue
                dctAdd[l4] = 0
                dctL1[l4] = 0
        l2 = dctAdd
lstCnt = []
for n in range(1,n + 1):
    cnt = 0
    for k in dctK[n]:
        if k in dctL[n]:
            cnt += 1
    lstCnt.append(cnt)
m = map(str,lstCnt)
print(" ".join(m))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)
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
    #木の深さじゃなく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())
load=UnionFind(n+1)
tetsu=UnionFind(n+1)
for _ in range(k):
    p,q=map(int,input().split())
    load.union(p,q)
for _ in range(l):
    r,s = map(int,input().split())
    tetsu.union(r,s)

count = [1]*n
for i in range(n):
    for j in load.members(i+1):
        if j!=i+1:
            if j in tetsu.members(i+1):
                count[i]+=1
print(*count)