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:
from itertools import product as prod

n, k, l = map(int, input().split())
con_k = [[False for _ in range(n)] for _ in range(n)]
con_l = [[False for _ in range(n)] for _ in range(n)]

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

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

m = n // 2 + 2
for ks in con_k:
    for i, j in prod(range(m), range(m)):
        if i != j and ks[i] and ks[j]:
            con_k[i][j] = True
            con_k[j][i] = True

for ls in con_l:
    for i, j in prod(range(m), range(m)):
        if i != j and ls[i] and ls[j]:
            con_l[i][j] = True
            con_l[j][i] = True

for (ks, ls) in zip(con_k, con_l):
    check = [k and l for k, l in zip(ks, ls)]
    ch_num = sum(check)
    print(ch_num + 1, end=" ")

Submission status: Time Limit Exceeded

Solution code:
from itertools import product as prod

n, k, l = map(int, input().split())
con_k = [[False for _ in range(n)] for _ in range(n)]
con_l = [[False for _ in range(n)] for _ in range(n)]

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

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

# m = n // 2 + 1
for ks in con_k:
    for i, j in prod(range(n), range(n)):
        if i != j and ks[i] and ks[j]:
            con_k[i][j] = True
            con_k[j][i] = True

for ls in con_l:
    for i, j in prod(range(n), range(n)):
        if i != j and ls[i] and ls[j]:
            con_l[i][j] = True
            con_l[j][i] = True

for (ks, ls) in zip(con_k, con_l):
    check = [k and l for k, l in zip(ks, ls)]
    ch_num = sum(check)
    print(ch_num + 1, end=" ")

Submission status: Time Limit Exceeded

Solution code:
from itertools import product as prod

n, k, l = map(int, input().split())
con_k = [[False for _ in range(n)] for _ in range(n)]
con_l = [[False for _ in range(n)] for _ in range(n)]

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

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

for k, i, j in prod(range(n), range(n), range(n)):
    if con_k[i][k] and con_k[k][j]:
        con_k[i][j] = True
        con_k[j][i] = True

for k, i, j in prod(range(n), range(n), range(n)):
    if con_l[i][k] and con_l[k][j]:
        con_l[i][j] = True
        con_l[j][i] = True

for (ks, ls) in zip(con_k, con_l):
    check = [k and l for k, l in zip(ks, ls)]
    ch_num = sum(check)
    print(ch_num + (ch_num == 0), end=" ")

Submission status: Time Limit Exceeded

Solution code:
class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))

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

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

    def unite(self, x, y):
        self.parent[self.root(x)]=self.root(y)


N, K, L = [int(n) for n in input().split()]

a = UnionFind(N)
b = UnionFind(N)
for i in range(K):
    p, q = [int(n)-1 for n in input().split()]
    a.unite(p, q)

for i in range(L):
    r, s = [int(n)-1 for n in input().split()]
    b.unite(r, s)

r=[[]]*N
for i in range(N):
    r[i]=[a.root(i), b.root(i)]



typecnt = {}
for i in range(N):
    if "{},{}".format(r[i][0],r[i][1]) in typecnt:
        typecnt["{},{}".format(r[i][0],r[i][1])] += 1
    else:
        typecnt["{},{}".format(r[i][0],r[i][1])]=1

res=[typecnt["{},{}".format(r[i][0],r[i][1])] for i in range(N)]
print(*res)

Submission status: Time Limit Exceeded

Solution code:
class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))

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

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

    def unite(self, x, y):
        self.parent[self.root(x)]=self.root(y)


N, K, L = [int(n) for n in input().split()]

ar = UnionFind(N)
br = UnionFind(N)
p=[0]*N
q=[0]*N
r=[0]*N
s=[0]*N
for i in range(K):
    p[i], q[i] = [int(n)-1 for n in input().split()]
    ar.unite(p[i], q[i])

for i in range(L):
    r[i], s[i] = [int(n)-1 for n in input().split()]
    br.unite(r[i], s[i])

res=[0]*N
for i in range(N):
    for j in range(N):
        if ar.root(i) == ar.root(j) and br.root(i) == br.root(j):
            res[i] += 1

print(*res)

Submission status: Time Limit Exceeded

Solution code:
class UnionFind:
    def __init__(self, N):
        self.root = [-1 for _ in xrange(N)]
        self.size = [1 for _ in xrange(N)]
        self.group = [set([i]) for i in xrange(N)]

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.size[x] < self.size[y]:
            self.root[x] = y
            self.size[y] += self.size[x]
            self.group[y] |= self.group[x]
        else:
            self.root[y] = x
            self.size[x] += self.size[y]
            self.group[x] |= self.group[y]

    def get_group(self, x):
        x = self.find(x)
        return self.group[x]

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

road = [map(int, raw_input().split()) for _ in range(K)]
train = [map(int, raw_input().split()) for _ in range(L)]

uf1 = UnionFind(N)
uf2 = UnionFind(N)

for p, q in road:
    uf1.union(p-1, q-1)

for r, s in train:
    uf2.union(r-1, s-1)

ans = []
for i in range(N):
    s1 = uf1.get_group(i)
    s2 = uf2.get_group(i)
    ans.append(len(s1 & s2))
print " ".join(map(str, ans))

Submission status: Time Limit Exceeded

Solution code:
class UnionFind:
	"""Union-Find, 
	http://www.slideshare.net/chokudai/union-find-49066733"""

	def __init__(self, N):
		self.par = [i for i in range(N)]

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

	def same(self, x, y):
		return self.par[x]==self.par[y]

	def unite(self, x, y):
		x = self.root(x)
		y = self.root(y)
		# if x==y:
		# 	return
		self.par[x] = y
		return

N, K, L = map(lambda x:int(x), input().split())
P = [0]*K
Q = [0]*K
R = [0]*L
S = [0]*L
for i in range(K):
	P[i], Q[i] = map(lambda x:int(x), input().split())
for i in range(L):
	R[i], S[i] = map(lambda x:int(x), input().split())

uf_k = UnionFind(N)
uf_l = UnionFind(N)

for i in range(K):
	uf_k.unite(P[i]-1, Q[i]-1)
for i in range(L):
	uf_l.unite(R[i]-1, S[i]-1)

k_groups = [uf_k.root(i) for i in range(N)]
l_groups = [uf_l.root(i) for i in range(N)]

num_kg = max(k_groups)
num_lg = max(l_groups)
result_tab = [[0 for j in range(num_lg+1)] for i in range(num_kg+1)]
for i in range(N):
	result_tab[k_groups[i]][l_groups[i]] = result_tab[k_groups[i]][l_groups[i]]+1
for i in range(N):
	kg = k_groups[i]
	lg = l_groups[i]
	print(result_tab[kg][lg], end=" ")

Submission status: Time Limit Exceeded

Solution code:
import sys

class UnionFind:

	def __init__(self, n):

		self.d=[-1 for i in range(n)]

	def root(self, v):

		if self.d[v] < 0:
			return v

		self.d[v] = self.root(self.d[v])

		return self.d[v]

	def unite(self, x, y):

		x = self.root(x)
		y = self.root(y)

		if x == y:
			return False

		if self.size(x) < self.size(y):
			x, y = y, x

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

		return True

	def size(self, v):

		return -(self.d[self.root(v)])

class Connecting:

    def get(self, N, K, L, pq, rs):

        
        uf1 = UnionFind(N)
        
        uf2 = UnionFind(N)

        
        for PQ in pq:
            uf1.unite(PQ[0]-1, PQ[1]-1)

        
        for RS in rs:
             uf2.unite(RS[0]-1, RS[1]-1)

        for i in range(N):
            ans = 0

            for j in range(1, N):
                if uf1.root(i) == uf1.root(j) and uf2.root(i) == uf2.root(j):
                    ans += 1

            if not ans:
                sys.stdout.write("1")
            else:
                sys.stdout.write(str(ans))
            sys.stdout.write(" ")

        sys.stdout.write("\n")

if __name__ == "__main__":

    N, K, L = [int(i) for i in raw_input().split()]
    pq = [[int(j) for j in raw_input().split()] for i in range(K)]
    rs = [[int(j) for j in raw_input().split()] for i in range(L)]

    abc = Connecting()
    abc.get(N, K, L, pq, rs)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools

class WarshallFloyd:

	def warshall_floyd(self, N):

		n = len(N)

		for i, j, k in itertools.product(range(n), range(n), range(n)):
			N[j][k] = min(N[j][k], N[j][i]+N[i][k])

		return N

class Connecting:

    def get(self, N, K, L, pq, rs):

        
        path_1 = [[float("inf") for j in range(N)] for i in range(N)]
       
        path_2 = [[float("inf") for j in range(N)] for i in range(N)]

        
        for i in range(N):
            path_1[i][i] = 0

        for PQ in pq:
            path_1[PQ[0]-1][PQ[1]-1] = 1
            path_1[PQ[1]-1][PQ[0]-1] = 1

       
        for i in range(N):
            path_2[i][i] = 0

        for RS in rs:
            path_2[RS[0]-1][RS[1]-1] = 1
            path_2[RS[1]-1][RS[0]-1] = 1

        wf = WarshallFloyd()
        path_1 = wf.warshall_floyd(path_1)
        path_2 = wf.warshall_floyd(path_2)

  
        for i in range(N):
            ans = 0

            for j in range(N):
                if path_1[i][j] != float("inf") and path_2[i][j] != float("inf"):
                    ans += 1

            sys.stdout.write(str(ans))
            sys.stdout.write(" ")

        sys.stdout.write("\n")

if __name__ == "__main__":

    N, K, L = [int(i) for i in raw_input().split()]
    pq = [[int(j) for j in raw_input().split()] for i in range(K)]
    rs = [[int(j) for j in raw_input().split()] for i in range(L)]

    abc = Connecting()
    abc.get(N, K, L, pq, rs)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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



city_street = np.arange(-1,-1*(N+1),-1)
num_street = 0
for i in range(0,K):
    #pi,qi = streets[i]
    pi,qi = map(int,input().split())
    pi  -= 1
    qi  -= 1
    if city_street[pi] * city_street[qi] < 0:
        city_street[pi] =  city_street[qi] = max(city_street[pi],city_street[qi])
    else:
        num_street +=1
        city_street[pi] =  city_street[qi] = num_street
        


city_rail = np.arange(-1,-1*(N+1),-1)
num_rail = 0
for i in range(0,K):
    #ri,si = rails[i]
    ri,si  = map(int,input().split())
    ri  -= 1
    si  -= 1
    if city_rail[ri] * city_rail[si] < 0:
        city_rail[ri] =  city_rail[si] = max(city_rail[ri],city_rail[si])
    else:
        if city_rail[ri] < 0:
            num_rail +=1
            city_rail[ri] =  city_rail[si] = num_rail
            

answers = []
for (i,num_street) in enumerate(city_street):
    temp_city_rail = city_rail +(city_street[i]- city_rail[i])
    rail_index = np.where(temp_city_rail == city_street[i])
    street_index = np.where(city_street == city_street[i])
    array = np.in1d(rail_index,street_index).tolist()
    answers.append(array.count(True))
     
print(str(answers).replace(',',' ')[1:-1])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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



city_street = np.arange(-1,-1*(N+1),-1)
num_street = 0
for i in range(0,K):
    #pi,qi = streets[i]
    pi,qi = map(int,input().split())
    pi  -= 1
    qi  -= 1
    if city_street[pi] * city_street[qi] < 0:
        city_street[pi] =  city_street[qi] = max(city_street[pi],city_street[qi])
    else:
        num_street +=1
        city_street[pi] =  city_street[qi] = num_street
        


city_rail = np.arange(-1,-1*(N+1),-1)
num_rail = 0
for i in range(0,K):
    #ri,si = rails[i]
    ri,si  = map(int,input().split())
    ri  -= 1
    si  -= 1
    if city_rail[ri] * city_rail[si] < 0:
        city_rail[ri] =  city_rail[si] = max(city_rail[ri],city_rail[si])
    else:
        if city_rail[ri] < 0:
            num_rail +=1
            city_rail[ri] =  city_rail[si] = num_rail
            

answers = []
for (i,num_street) in enumerate(city_street):
    temp_city_rail = city_rail +(city_street[i]- city_rail[i])
    answers.append( len([index for index in range(0,N) if city_street[index] == city_street[i] and  temp_city_rail[index]== city_street[i]]))
   


    
    #answers.append(a)
    
print(str(answers).replace(',',' ')[1:-1])

Submission status: Time Limit Exceeded

Solution code:
def find(num, mat):
    for s in mat:
        if num in s:
            return s
    return {num}


def cap(kl):
    mat = []
    for i in range(kl):
        a, b = map(int, input().split())
        for s in mat:
            if a in s or b in s:
                s |= {a, b}
                break
        else:
            mat.append({a, b})

    return mat


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

m = cap(k)
m2 = cap(l)

print(" ".join(map(str, [len(find(i + 1, m) & find(i + 1, m2)) for i in range(n)])))

Submission status: Time Limit Exceeded

Solution code:
def cap(mat):
    for i in range(k):
        a, b = map(int, input().split())
        mat[a - 1].add(b)
        mat[b - 1].add(a)

    for ni, i in enumerate(mat):
        s = i.copy()
        for e in i:
            s |= mat[e-1]
        mat[ni] = s

    return mat


n, k, l = map(int, input().split())
m = [{i + 1} for i in range(n)]
m2 = [{i + 1} for i in range(n)]

print(" ".join(map(str, [len(s & s2) for s, s2 in zip(cap(m), cap(m2))])))

Submission status: Time Limit Exceeded

Solution code:
def test(mat):
    for n, i in enumerate(mat):
        for en, e in enumerate(i):
            if e:
                mat[n] = [x + y for x, y in zip(i, mat[en])]

    return [{t[0] + 1 for t in enumerate(i) if t[1]} for i in mat]


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

m = [[1 if i == j else 0 for i in range(n)] for j in range(n)]
m2 = [[1 if i == j else 0 for i in range(n)] for j in range(n)]

for i in range(k):
    a, b = map(int, input().split())
    m[a - 1][b - 1] = 1
    m[b - 1][a - 1] = 1

for i in range(l):
    a, b = map(int, input().split())
    m2[a - 1][b - 1] = 1
    m2[b - 1][a - 1] = 1

m = test(m)
m2 = test(m2)

print(" ".join(map(str,[len(s & s2) for s, s2 in zip(m, m2)])))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
n,k,l = map(int, input().split())
def f(m):
    a = [[] for _ in range(n)]
    for _ in range(m):
        p,q = map(int, input().split())
        a[p-1].append(q-1)
        a[q-1].append(p-1)
    b = list(range(n))
    for i in range(n):
        s = [i]
        while s:
            j = s.pop()
            if b[j] != j:
                continue
            b[j] = i
            for k in a[j]:
                s.append(k)
    return b
a = f(k)
b = f(l)
c = Counter((a[i],b[i]) for i in range(n))
print(' '.join((str(c[a[i],b[i]]) for i in range(n))))

Submission status: Time Limit Exceeded

Solution code:
def search_group(target, group):
    for index in range(len(group)):
        if target in group[index]:
            return index
        
def exclude_repeated(group_number, group):
    for index in range(group_number):
        (t1, t2) = input().split(" ")
        t1 = int(t1)
        t2 = int(t2)
        g1 = search_group(t1, group)
        g2 = search_group(t2, group)
        if g1 == g2:
            continue
        else:
            group[g1] += group[g2]
            del group[g2]
            continue

    
(city, road, rail) = input().split(" ")
city = int(city)
road = int(road)
rail = int(rail)

road_group = []
rail_group = []
for index in range(1, city + 1):
    road_group.append([index])
    rail_group.append([index])

exclude_repeated(road, road_group)
exclude_repeated(rail, rail_group)

for index in range(1, city + 1):
    g1 = search_group(index, road_group)
    g2 = search_group(index, rail_group)
    tset = set(road_group[g1]) & set(rail_group[g2])
    print(len(tset), end = ' ')

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python

import sets
import sys

def main(argv):
    tokens = sys.stdin.readline().rstrip("\n").split(" ")

    while len(tokens) == 3:
        n, k, l = map(lambda x: int(x), tokens)

        roads = [i for i in xrange(n)]
        railways = [i for i in xrange(n)]

        for i in xrange(k):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            if roads[y - 1] > roads[x - 1]:
                roads[y - 1] = roads[x - 1]
            else:
                roads[x - 1] = roads[y - 1]

        for i in xrange(l):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            if railways[y - 1] > railways[x - 1]:
                railways[y - 1] = railways[x - 1]
            else:
                railways[x - 1] = railways[y - 1]

        results = [0 for i in xrange(n)]
        for i in xrange(n):
            for j in xrange(n):
                if roads[i] == roads[j] and railways[i] == railways[j]:
                    results[i] += 1
        results = map(lambda r: str(r), results)
        print " ".join(results)

        tokens = sys.stdin.readline().rstrip("\n").split(" ")

if __name__ == "__main__":
    main(sys.argv)

Submission status: Time Limit Exceeded

Solution code:
passed=set([])
def search(goal,path,adj):
    global passed
    n=path[-1]
    if goal==n:
        passed=passed.union(path)
    else:
        for x in adj[n]:
            if x not in path:
                path.append(x)
                search(goal,path,adj)
                path.pop()
    
adj_r=[]
adj_t=[]
passed_r=[]
passed_t=[]
N,K,L=map(int,raw_input().split())

for _ in range(0,N):
    adj_r.append(set())
    adj_t.append(set())
    passed_r.append(set())
    passed_t.append(set())


max_len=N-1

for _ in range(0,K):
    p=map(int,raw_input().split())
    adj_r[p[0]-1].add(p[1]-1)
    adj_r[p[1]-1].add(p[0]-1)

for _ in range(0,L):
    p=map(int,raw_input().split())
    adj_t[p[0]-1].add(p[1]-1)
    adj_t[p[1]-1].add(p[0]-1)
for i in range(0,N):
    for j in range(0,N):
        search(j,[i],adj_r)
        passed_r[i]=passed_r[i].union(passed)
        passed=set([])
        search(j,[i],adj_t)
        passed_t[i]=passed_t[i].union(passed)
        passed=set([])

for (r,t) in zip(passed_r,passed_t):
    print len(r&t),
    

print ""

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python

import sets
import sys

def main(argv):
    tokens = sys.stdin.readline().rstrip("\n").split(" ")

    while len(tokens) == 3:
        n, k, l = map(lambda x: int(x), tokens)

        roads = [set([i]) for i in xrange(n)]
        railways = [set([i]) for i in xrange(n)]

        for i in xrange(0, k):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            if roads[x - 1] != roads[y - 1]:
                roads[x - 1].update(roads[y - 1])
                for j in roads[y - 1]:
                    roads[j] = roads[x - 1]

        for i in xrange(0, l):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            if railways[x - 1] != railways[y - 1]:
                railways[x - 1].update(railways[y - 1])
                for j in railways[y - 1]:
                    railways[j] = railways[x - 1]

        results = []
        for i in xrange(0, n):
            results.append(str(len(roads[i].intersection(railways[i]))))
        print " ".join(results)

        tokens = sys.stdin.readline().rstrip("\n").split(" ")
if __name__ == "__main__":
    main(sys.argv)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python

import sets
import sys

def main(argv):
    tokens = sys.stdin.readline().rstrip("\n").split(" ")

    while len(tokens) == 3:
        n, k, l = map(lambda x: int(x), tokens)

        roads = [set([i]) for i in xrange(n)]
        railways = [set([i]) for i in xrange(n)]

        for i in xrange(0, k):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            roads[x - 1].add(y - 1)

        for i in xrange(0, l):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            railways[x - 1].add(y - 1)

        for i in xrange(0, n):
            for j in list(roads[i]):
                roads[i].update(roads[j])
                roads[j] = roads[i]

            for j in list(railways[i]):
                railways[i].update(railways[j])
                railways[j] = railways[i]

        results = []
        for i in xrange(0, n):
            results.append(str(len(roads[i].intersection(railways[i]))))
        print " ".join(results)

        tokens = sys.stdin.readline().rstrip("\n").split(" ")
if __name__ == "__main__":
    main(sys.argv)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python

import sets
import sys

def main(argv):
    tokens = sys.stdin.readline().rstrip("\n").split(" ")

    while len(tokens) == 3:
        n, k, l = map(lambda x: int(x), tokens)

        roads = [set([i]) for i in xrange(n)]
        railways = [set([i]) for i in xrange(n)]

        for i in xrange(0, k):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            roads[x - 1].update(roads[y - 1])
            for j in roads[y - 1]:
                roads[j] = roads[x - 1]

        for i in xrange(0, l):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            railways[x - 1].update(railways[y - 1])
            for j in railways[y - 1]:
                railways[j] = railways[x - 1]

        results = []
        for i in xrange(0, n):
            results.append(str(len(roads[i].intersection(railways[i]))))
        print " ".join(results)

        tokens = sys.stdin.readline().rstrip("\n").split(" ")
if __name__ == "__main__":
    main(sys.argv)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python

import sets
import sys

def main(argv):
    tokens = sys.stdin.readline().rstrip("\n").split(" ")

    while len(tokens) == 3:
        n, k, l = map(lambda x: int(x), tokens)

        roads = [set([i]) for i in xrange(n)]
        railways = [set([i]) for i in xrange(n)]

        for i in xrange(0, k):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            roads[x - 1].add(y - 1)

        for i in xrange(0, l):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            railways[x - 1].add(y - 1)

        for i in xrange(0, n):
            for j in roads[i]:
                if i != j:
                    roads[j] = roads[j].union(roads[i])

            for j in railways[i]:
                if i != j:
                    railways[j] = railways[j].union(railways[i])

        results = []
        for i in xrange(0, n):
            results.append(str(len(roads[i].intersection(railways[i]))))
        print " ".join(results)

        tokens = sys.stdin.readline().rstrip("\n").split(" ")
if __name__ == "__main__":
    main(sys.argv)

Submission status: Time Limit Exceeded

Solution code:
N,K,L = map(int, input().split() )
doro=[]
senro=[]

for i in range(K):
    a,b=map(int, input().split())
    doro.append([a,b])

for i in range(L):
    a,b=map(int, input().split())
    senro.append([a,b])


def sab_d(a,b):
    for x in Doro[b-1]:
        if (x in Doro[a-1])==False:
            Doro[a-1].append(x)
    for y in Doro[a-1]:
        if (y in Doro[b-1])==False:
            Doro[b-1].append(y)
    return()

def sab_s(a,b):
    for x in Senro[b-1]:
        if (x in Senro[a-1])==False:
            Senro[a-1].append(x)
    for y in Senro[a-1]:
        if (y in Senro[b-1])==False:
            Senro[b-1].append(y)
    return()


Doro=[]
Senro=[]

for i in range(N):
    Doro.append([i+1])
for i in range(N):
    Senro.append([i+1])


for i in range(K):
    a=doro[i][0]
    b=doro[i][1]
    sab_d(a,b)
for i in range(K):
    a=doro[i][0]
    b=doro[i][1]
    sab_d(a,b)

for i in range(L):
    a=senro[i][0]
    b=senro[i][1]
    sab_s(a,b)
for i in range(L):
    a=senro[i][0]
    b=senro[i][1]
    sab_s(a,b)


result = []

for i in range(N):
    result.append( len([tag for tag in Doro[i] if tag in Senro[i]]) )
for i in range(N):
    print(result[i],end=" ")

Submission status: Time Limit Exceeded

Solution code:
N,K,L = map(int, input().split() )
doro=[]
senro=[]

for i in range(K):
    a,b=map(int, input().split())
    doro.append([a,b])

for i in range(L):
    a,b=map(int, input().split())
    senro.append([a,b])


def sab_d(a,b):
    for x in Doro[b-1]:
        if (x in Doro[a-1])==False:
            Doro[a-1].append(x)
    for y in Doro[a-1]:
        if (y in Doro[b-1])==False:
            Doro[b-1].append(y)
    return()

def sab_s(a,b):
    for x in Senro[b-1]:
        if (x in Senro[a-1])==False:
            Senro[a-1].append(x)
    for y in Senro[a-1]:
        if (y in Senro[b-1])==False:
            Senro[b-1].append(y)
    return()


Doro=[]
Senro=[]

for i in range(N):
    Doro.append([i+1])
for i in range(N):
    Senro.append([i+1])


for i in range(K):
    a=doro[i][0]
    b=doro[i][1]
    sab_d(a,b)
for i in range(K):
    a=doro[i][0]
    b=doro[i][1]
    sab_d(a,b)

for i in range(L):
    a=senro[i][0]
    b=senro[i][1]
    sab_s(a,b)
for i in range(L):
    a=senro[i][0]
    b=senro[i][1]
    sab_s(a,b)



result = []

for i in range(N):
    count=0
    a=Doro[i]
    b=Senro[i]
    for j in a:
        if (j in b)==True:
            count += 1 
    result.append(count)

for i in range(N):
    print(result[i],end=" ")

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from concurrent import futures
import sys

class DFS:
    def __init__(self, adjacent):
        self.adjacent = adjacent
        self.table = [0] * len(adjacent)
        self.group = 0
        for i in range(len(adjacent)):
            if self.table[i] == 0:
                self.group += 1
                self.dfs(i)

    def dfs(self, node):
        if self.table[node] == 0:
            self.table[node] = self.group
            for x in self.adjacent[node]:
                self.dfs(x)

    def find(self, x): return self.table[x]
    def getTableSet(self): return self.table

if __name__ == '__main__':
    sys.setrecursionlimit(100000)

    n, k, l = map(int, input().split())
    loadlist = [[] for _ in range(n)]
    trainlist = [[] for _ in range(n)]
    to_i = lambda x: int(x) - 1
    for p, q in [map(to_i, input().split()) for _ in range(k)]:
        loadlist[p].append(q)
        loadlist[q].append(p)
    for r, s in [map(to_i, input().split()) for _ in range(l)]:
        trainlist[r].append(s)
        trainlist[s].append(r)

    s = DFS(loadlist)
    loadresult = {-1: []}
    loadresultDic = defaultdict(lambda: -1)

    t = DFS(trainlist)
    trainresult = {-1: []}
    trainresultDic = defaultdict(lambda: -1)

    for i in range(n):
        result = s.find(i)
        if result in loadresult:
            loadresult[result].append(i)
        else:
            loadresult[result] = [i]
        loadresultDic[i] = result

        result = t.find(i)
        if result in trainresult:
            trainresult[result].append(i)
        else:
            trainresult[result] = [i]
        trainresultDic[i] = result


    print(" ".join([str(len(set(loadresult[loadresultDic[i]]) & \
                    set(trainresult[trainresultDic[i]]))) for i in range(n)]))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from concurrent import futures
import sys

class DFS:
    def __init__(self, adjacent):
        self.adjacent = adjacent
        self.table = [0] * len(adjacent)
        self.group = 0
        for i in range(len(adjacent)):
            if self.table[i] == 0:
                self.group += 1
                self.dfs(i)

    def dfs(self, node):
        if self.table[node] == 0:
            self.table[node] = self.group
            for x in self.adjacent[node]:
                self.dfs(x)

    def find(self, x): return self.table[x]
    def getTableSet(self): return self.table

if __name__ == '__main__':
    sys.setrecursionlimit(100000)

    n, k, l = map(int, input().split())
    loadlist = [[] for _ in range(n)]
    trainlist = [[] for _ in range(n)]
    for _ in range(k):
        p, q = map(lambda x: int(x) - 1, input().split())
        loadlist[p].append(q)
        loadlist[q].append(p)
    for _ in range(l):
        r, s = map(lambda x: int(x) - 1, input().split())
        trainlist[r].append(s)
        trainlist[s].append(r)

    s = DFS(loadlist)
    loadresult = {-1: []}
    loadresultDic = defaultdict(lambda: -1)

    t = DFS(trainlist)
    trainresult = {-1: []}
    trainresultDic = defaultdict(lambda: -1)

    for i in range(n):
        result = s.find(i)
        if result in loadresult:
            loadresult[result].append(i)
        else:
            loadresult[result] = [i]
        loadresultDic[i] = result

        result = t.find(i)
        if result in trainresult:
            trainresult[result].append(i)
        else:
            trainresult[result] = [i]
        trainresultDic[i] = result


    print(" ".join([str(len(set(loadresult[loadresultDic[i]]) & \
                    set(trainresult[trainresultDic[i]]))) for i in range(n)]))