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: Runtime Error

Solution code:
# coding: utf-8
# Your code here!
from collections import Counter
from collections import defaultdict

n,k,l=map(int,input().split())
p=[0]*(k+1)
q=[0]*(k+1)
rd=[[] for _ in range(n+1)]
r=[0]*(l+1)
s=[0]*(l+1)
rw=[[] for _ in range(n+1)]

for i in range(k):
    a,b=map(int,input().split())
    p[i],q[i]=a,b
    rd[a].append(b)
    rd[b].append(a)
for i in range(l):
    a,b=map(int,input().split())
    r[i],s[i]=a,b
    rw[a].append(b)
    rw[b].append(a)

prd=[i for i in range(n+1)]
prw=[i for i in range(n+1)]

def union(x,y):
    rx=root(x)
    ry=root(y)
    if rx==ry:
        return
    p[rx]=ry
    
def root(x):
    if p[x]==x:
        return x
    p[x]=root(p[x])
    return p[x]
    
cnt=[[] for _ in range(n+1)]
#print(rd)
#print(rw)

p=prd
for i in range(1,n+1):
    for j in rd[i]:
        union(i,j)
for i in range(1,n+1):
    rt=root(i)
    prd[i]=rt
    cnt[i].append(rt)

p=prw
for i in range(1,n+1):
    for j in rw[i]:
        union(i,j)
for i in range(1,n+1):
    rt=root(i)
    prw[i]=rt
    cnt[i].append(rt)
#print(cnt)
#c=Counter(cnt)
dc=defaultdict(int)
for i in cnt:
    dc[','.join([str(c) for c in i])] += 1

#for i in range(n+1):
print(*[dc[','.join([str(c) for c in cnt[i]])] for i in range(1,n+1)])

Submission status: Runtime Error

Solution code:
#include "bits/stdc++.h"
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;

typedef long long ll;

const int MAX_N = 200001;
int par[MAX_N];
int rnk[MAX_N];

void init(int n) {
    rep(i,n) {
        par[i] = i;
        rnk[i] = 0;
    }
}

int find(int x) {
    if (par[x] == x) {
        return x;
    } else {
        return par[x] = find(par[x]);
    }
}

void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (rnk[x] < rnk[y]) {
        par[x] = y;
    } else {
        par[y] = x;
        if (rnk[x] == rnk[y]) rnk[x]++;
    }
}

bool same(int x, int y) {
    return find(x) == find(y);
}

void solve() {
    int N, K, L, p, q;
    cin >> N >> K >> L;
    init(N);
    rep(i,K) {
        cin >> p >> q;
        unite(p - 1, q - 1);
    }
    int roads[N];
    rep(i,N) roads[i] = find(i);
    init(N);
    rep(i,L) {
        cin >> p >> q;
        unite(p - 1, q - 1);
    }
    map<pair<int, int>, int> d;
    rep(i,N) d[make_pair(roads[i], find(i))]++;
    rep(i,N) cout << d[make_pair(roads[i], find(i))] << " ";
    cout << endl;
    return;
}

int main() {
    solve();
}

Submission status: Runtime Error

Solution code:
from collections import defaultdict as dd
road = dd(list)
train = dd(list)
def gr(tree,start):
    island = set()
    rest = [start,]
    while rest:
        node = rest.pop()
        island.add(node)
        for x in tree[node]:
            if x not in island:
                rest.append(x)
    return(island)
n,k,l = map(int, input().split())
for _ in range(k):
    a,b = map(int,input().split())
    road[a].append(b)
    road[b].append(a)
for _ in range(k):
    a,b = map(int,input().split())
    train[a].append(b)
    train[b].append(a)
for i in range(1,n+1):
    print(len(gr(road,i)&gr(train,i)))

Submission status: Runtime Error

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


class UFT:
    def __init__(self, N):
        self.UFdata = [-1] * (N+1)
        self.rank   = [0]  * (N+1)

    def find(self,x):
        UFdata = self.UFdata
        while UFdata[x] != -1:
            x = UFdata[x]
        return x

    def unite(self,x,y):
        UFdata = self.UFdata
        rank = self.rank 
        find = self.find

        x = find(x)
        y = find(y)
        if x != y:
            if rank[x] < rank[y]:
                x,y = y,x
            if rank[x] == rank[y]:
                rank[x] += 1
            UFdata[y] = x       
            

UF1 = UFT(N)
UF2 = UFT(N)
ans = [1] * (N+1)
MAP= [ [0] * (N+1) for _ in range(N+1)]
import sys
input = sys.stdin.readline
#PQ = [ [int(j) for j in input().split()] for _ in range(K)]
#RS = [ [int(j) for j in input().split()] for _ in range(L)]

for i in range(K):
    p,q = map(int,input().split())
    UF1.unite(p,q)
for i in range(L):
    p,q = map(int,input().split())#RS[i]
    UF2.unite(p, q)
counter=[]
from collections import defaultdict
cntdic =defaultdict(int)
for i in range(1,N+1):
  counter.append(UF1.find(i)+UF2.find(i)*10**6)
  cntdic[counter[-1]]+=1 

ans = [0]*(N+1)
for i in range(1,N+1):
    ans[i] = cntdic[UF1.find(i)+UF2.find(i)*10**6]

del ans[0]
# print(" ".join( map(lambda x: str(x), connected_num[1:])))
print(" ".join( map(lambda x: str(x), ans)))

Submission status: Runtime Error

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


class UFT:
    def __init__(self, N):
        self.UFdata = [-1] * (N+1)
        self.rank   = [0]  * (N+1)

    def find(self,x):
        UFdata = self.UFdata
        while UFdata[x] != -1:
            x = UFdata[x]
        return x

    def unite(self,x,y):
        UFdata = self.UFdata
        rank = self.rank 
        find = self.find

        x = find(x)
        y = find(y)
        if x != y:
            if rank[x] < rank[y]:
                x,y = y,x
            if rank[x] == rank[y]:
                rank[x] += 1
            UFdata[y] = x       
            

UF1 = UFT(N)
UF2 = UFT(N)
ans = [1] * (N+1)
MAP= [ [0] * (N+1) for _ in range(N+1)]
import sys
input = sys.stdin.readline
PQ = [ [int(j) for j in input().split()] for _ in range(K)]
RS = [ [int(j) for j in input().split()] for _ in range(L)]

for i in range(K):
    p,q = PQ[i]
    UF1.unite(p,q)
for i in range(L):
    p,q = RS[i]
    UF2.unite(p, q)
counter=[]
from collections import defaultdict
cntdic =defaultdict(int)
for i in range(1,N+1):
  counter.append(UF1.find(i)+UF2.find(i)*10**6)
  cntdic[counter[-1]]+=1 

ans = [0]*(N+1)
for i in range(1,N+1):
    ans[i] = cntdic[counter[i-1]]

del ans[0]
# print(" ".join( map(lambda x: str(x), connected_num[1:])))
print(" ".join( map(lambda x: str(x), ans)))

Submission status: Runtime Error

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


class UFT:
    def __init__(self, N):
        self.UFdata = [-1] * (N+1)
        self.rank   = [0]  * (N+1)

    def find(self,x):
        UFdata = self.UFdata
        while UFdata[x] != -1:
            x = UFdata[x]
        return x

    def unite(self,x,y):
        UFdata = self.UFdata
        rank = self.rank 
        find = self.find

        x = find(x)
        y = find(y)
        if x != y:
            if rank[x] < rank[y]:
                x,y = y,x
            if rank[x] == rank[y]:
                rank[x] += 1
            UFdata[y] = x       
            

UF1 = UFT(N)
UF2 = UFT(N)
ans = [1] * (N+1)
MAP= [ [0] * (N+1) for _ in range(N+1)]
import sys
input = sys.stdin.readline
PQ = [ [int(j) for j in input().split()] for _ in range(K)]
RS = [ [int(j) for j in input().split()] for _ in range(L)]

for i in range(K):
    p,q = PQ[i]
    UF1.unite(p,q)
for i in range(L):
    p,q = RS[i]
    UF2.unite(p, q)
counter=[]
from collections import defaultdict
cntdic =defaultdict(int)
for i in range(1,N+1):
  counter.append(UF1.find(i)+UF2.find(i)*10**6)
  cntdic[counter[-1]]+=1 

ans = [0]*(N+1)
for i in range(1,N+1):
    ans[i] = cntdic[counter[i]]

del ans[0]
# print(" ".join( map(lambda x: str(x), connected_num[1:])))
print(" ".join( map(lambda x: str(x), ans)))

Submission status: Runtime Error

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


class UFT:
    def __init__(self, N):
        self.UFdata = [-1] * (N+1)
        self.rank   = [0]  * (N+1)

    def find(self,x):
        UFdata = self.UFdata
        while UFdata[x] != -1:
            x = UFdata[x]
        return x

    def unite(self,x,y):
        UFdata = self.UFdata
        rank = self.rank 
        find = self.find

        x = find(x)
        y = find(y)
        if x != y:
            if rank[x] < rank[y]:
                x,y = y,x
            if rank[x] == rank[y]:
                rank[x] += 1
            UFdata[y] = x       
            

UF1 = UFT(N)
UF2 = UFT(N)
ans = [1] * (N+1)
MAP= [ [0] * (N+1) for _ in range(N+1)]
import sys
input = sys.stdin.readline
PQ = [ [int(j) for j in input().split()] for _ in range(K)]
RS = [ [int(j) for j in input().split()] for _ in range(L)]

for i in range(K):
    p,q = PQ[i]
    UF1.unite(p,q)
for i in range(L):
    p,q = RS[i]
    UF2.unite(p, q)
counter=[]
for i in range(1,N+1):
  counter.append((UF1.find(i),UF2.find(i)))
from collections import Counter  
p=Counter(counter)

ans = [0]*(N+1)
for i in range(1,N+1):
    ans[i] = p[(UF1.find(i),UF2.find(i))]

del ans[0]
# print(" ".join( map(lambda x: str(x), connected_num[1:])))
print(" ".join( map(lambda x: str(x), ans)))

Submission status: Runtime Error

Solution code:
def inpl(): return [int(i) for i in input().split()]

def root(x,par):
    if par[x] == x:
        return [x,[x]]
    else:
        return [root(par[x],par)[0],root(par[x],par)[1]+[x]]


N, K, L = inpl()
parK = list(range(N))
for i in range(K):
    p, q = inpl()
    rp = root(p-1,parK)
    rq = root(q-1,parK)
    if len(rp[1]) < len(rq[1]) :
        parK[rq[0]] = rp[0] 
    else:
        parK[rp[0]] = rq[0]
    print(parK)

parL = list(range(N))
for i in range(L):
    r, s = inpl()
    rr = root(r-1,parL)
    rs = root(s-1,parL)
    for i in rr[1]:
        parL[i] = rr[0]
    for j in rs[1]:
        parL[j] = rr[0]

from collections import defaultdict
ans = defaultdict(lambda: 0)
for i in range(N):
    ans[root(i,parK)[0],root(i,parL)[0]] +=1
Ans = [0 for _ in range(N)]
for i in range(N):
    Ans[i] = ans[root(i,parK)[0],root(i,parL)[0]]
print(*Ans)

Submission status: Runtime Error

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10**5)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

class UnionFind:
    def __init__(self, node:int) -> None:
        self.n = node
        self.par = [i for i in range(self.n)]
        self.rank = [0 for i in range(self.n)]
        
    def find(self, x:int) -> int:
        if x == self.par[x]:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
        
    def unite(self, x:int, y:int) -> bool:
        if self.isSame(x,y):
            #print("x and y has already united")
            return False
        
        rx = self.find(x)
        ry = self.find(y)
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = self.par[ry]
        else:
            self.par[ry] = self.par[rx]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1
                
        return True
                
    def isSame(self, x:int, y:int) -> bool:
        return self.find(x) == self.find(y)
    
n,k,l = li()
pq = []
rs = []

for _ in range(k):
    pq.append(tuple(li_()))
    
for _ in range(l):
    rs.append(tuple(li_()))

road = UnionFind(n)
rail = UnionFind(n)

for p,q in pq:
    road.unite(p,q)
    
for r,s in rs:
    rail.unite(r,s)
    
for i in range(k):
    road.find(i)
    
for i in range(l):
    rail.find(i)
    
road_dic = {i:set() for i in range(n)}
rail_dic = {i:set() for i in range(n)}

for i in range(n):
    road_dic[road.par[i]].add(i)
    rail_dic[rail.par[i]].add(i)
    
ans = []
for i in range(n):
    ans.append(len(road_dic[road.par[i]] & rail_dic[rail.par[i]]))
    
print(*ans)

Submission status: Runtime Error

Solution code:

N,K,L=map(int,input().split())
len = [[[] for s in range(N)] for t in range (2)]
i=1
j=1
while i <= K:
    a,b=map(int,input().split())
    len[0][a-1].append(b-1)
    len[0][b-1].append(a-1)
    i+=1

while j <= L:
    a,b=map(int,input().split())
    len[1][a-1].append(b-1)
    len[1][b-1].append(a-1)
    j+=1

def add(z,n):
    for num1 in len[z][n]:
        for num2 in len[z][num1]:
            if num2 != n and num2 not in len[z][n]:
                len[z][n].append(num2)
                add(z,num2)

n=0
while n < N:
    add(0,0)
    add(1,0)
    n+=1

n=0
answer=[1]*N
while n < N:
    for point in len[0][n]:
        if point in len[1][n]:
            answer[n]+=1
    n+=1

n=0
while n<N-1:
    print(answer[n],end=' ')
    n+=1
print(answer[N-1])

Submission status: Runtime Error

Solution code:

N,K,L=map(int,input().split())
len = [[[] for s in range(N)] for t in range (2)]
i=1
j=1
while i <= K:
    a,b=map(int,input().split())
    len[0][a-1].append(b-1)
    len[0][b-1].append(a-1)
    i+=1

while j <= L:
    a,b=map(int,input().split())
    len[1][a-1].append(b-1)
    len[1][b-1].append(a-1)
    j+=1

def add(z,n):
    for num1 in len[z][n]:
        for num2 in len[z][num1]:
            if num2 != n and num2 not in len[z][n]:
                len[z][n].append(num2)
                add(z,num2)
n=0
while n < N:
  add(0,n)
  add(1,n)
  n+=1

n=0
answer=[1]*N
while n < N:
    for point in len[0][n]:
        if point in len[1][n]:
            answer[n]+=1
    n+=1

n=0
while n<N-1:
    print(answer[n],end=' ')
    n+=1
print(answer[N-1])

Submission status: Runtime Error

Solution code:

N,K,L=map(int,input().split())
len = [[[] for s in range(N)] for t in range (2)]
i=1
j=1
while i <= K:
    a,b=map(int,input().split())
    len[0][a-1].append(b-1)
    len[0][b-1].append(a-1)
    i+=1

while j <= L:
    a,b=map(int,input().split())
    len[1][a-1].append(b-1)
    len[1][b-1].append(a-1)
    j+=1

def add(z,n):
    for num1 in len[z][n]:
        for num2 in len[z][num1]:
            if num2 != n and num2 not in len[z][n]:
                len[z][n].append(num2)
                add(z,num2)
n=0
while n < N:
	add(0,n)
    add(1,n)
    n+=1

n=0
answer=[1]*N
while n < N:
    for point in len[0][n]:
        if point in len[1][n]:
            answer[n]+=1
    n+=1

n=0
while n<N-1:
    print(answer[n],end=' ')
    n+=1
print(answer[N-1])

Submission status: Runtime Error

Solution code:

N,K,L=map(int,input().split())
len = [[[] for s in range(N)] for t in range (2)]
i=1
j=1
while i <= K:
    a,b=map(int,input().split())
    len[0][a-1].append(b-1)
    len[0][b-1].append(a-1)
    i+=1

while j <= L:
    a,b=map(int,input().split())
    len[1][a-1].append(b-1)
    len[1][b-1].append(a-1)
    j+=1

def add(z,n):
    for num1 in len[z][n]:
        for num2 in len[z][num1]:
            if num2 != n and num2 not in len[z][n]:
                len[z][n].append(num2)
                add(z,num2)
n=0
while n < N:
	add(0,n)
	add(1,n)
    n+=1

n=0
answer=[1]*N
while n < N:
    for point in len[0][n]:
        if point in len[1][n]:
            answer[n]+=1
    n+=1

n=0
while n<N-1:
    print(answer[n],end=' ')
    n+=1
print(answer[N-1])

Submission status: Runtime Error

Solution code:

N,K,L=map(int,input().split())
len = [[[] for s in range(N)] for t in range (2)]
i=1
j=1
while i <= K:
    a,b=map(int,input().split())
    len[0][a-1].append(b-1)
    len[0][b-1].append(a-1)
    i+=1

while j <= L:
    a,b=map(int,input().split())
    len[1][a-1].append(b-1)
    len[1][b-1].append(a-1)
    j+=1

def add(z,n):
    for num1 in len[z][n]:
        for num2 in len[z][num1]:
            if num2 != n and num2 not in len[z][n]:
                len[z][n].append(num2)
                add(z,num2)

add(0,0)
add(1,0)

n=0
answer=[1]*N
while n < N:
    for point in len[0][n]:
        if point in len[1][n]:
            answer[n]+=1
    n+=1

n=0
while n<N-1:
    print(answer[n],end=' ')
    n+=1
print(answer[N-1])

Submission status: Runtime Error

Solution code:
v\from collections import defaultdict
N, K, L = map(int, input().split())


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

    # 検索
    def find(self, 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 = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
            self.size[x] = 0
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            self.size[y] = 0
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # すべての頂点に対して親を検索する
    def all_find(self):
        for n in range(len(self.par)):
            self.find(n)


UF1 = UnionFind(N)
UF2 = UnionFind(N)

for k in range(K):
    p, q = map(int, input().split())
    p, q = p-1, q-1
    UF1.union(p, q)
for l in range(L):
    r, s = map(int, input().split())
    r, s = r-1, s-1
    UF2.union(r, s)

UF1.all_find()
UF2.all_find()

D = defaultdict(int)
for p1, p2 in zip(UF1.par, UF2.par):
    D[(p1, p2)] += 1

ans = [D[(p1, p2)] for p1, p2 in zip(UF1.par, UF2.par)]
print(*ans)

Submission status: Runtime Error

Solution code:
# 頂点 v の所属するグループを調べる
def root(v):
  if uni[v] < 0:  # v が親の場合
    return v
  else:           # v が子の場合
    uni[v] = root(uni[v])  # 親のrootを調べる
    return uni[v]

# 頂点 a と頂点 b をつなぐ。もともと同じグループのとき、False を返す
def connect(a, b):
  # まずはそれぞれ根の番号に置き換える
  ra = root(a)
  rb = root(b)
  if ra == rb:  # a と b がそもそも同じグループに属しているなら即終了
    return False
	
  # ra を大きなグループにしたいので、逆であれば入れ替える
  if uni[ra] > uni[rb]: # rbの方が要素数が多ければ
    tmp = ra
    ra  = rb 
    rb  = tmp

  # ra と rb を結合し、rb の親を ra とする
  uni[ra] += uni[rb]
  uni[rb] = ra
  return True
      
##
N, K, L = map(int, input().split())

road = [-1]*(N+1)
rail = [-1]*(N+1)

for i in range(K):
  a, b = map(int, input().split())
  connect(a, b, road)

for i in range(L):
  a, b = map(int, input().split())
  connect(a, b, rail)


##
dp = [0]*(N+1)
for i in range(1, N+1):
  dp[i] = (root(i, road), root(i, rail))

dic = {}
for i in range(1, N+1):
  key = dp[i]
  if key not in dic:
    dic[key] = 1
  else:
    dic[key] += 1

for i in range(1, N+1):
  ans = dic[dp[i]]
  if i == N:
    print(ans)
  else:
    print(ans, end=" ")

Submission status: Runtime Error

Solution code:
n,k,l=map(int,raw_input().split())
e1=[[] for i in range(n)]
e2=[[] for i in range(n)]
for i in range(k):
    p,q=map(int,raw_input().split())
    e1[p-1].append(q-1)
    e1[q-1].append(p-1)
for i in range(l):
    p,q=map(int,raw_input().split())
    e2[p-1].append(q-1)
    e2[q-1].append(p-1)
num1=[0]*n
num2=[0]*n
def dfs1(x,i):
    num1[x]=i
    for node in e1[x]:
        if num1[node]==0:dfs1(node,i)
def dfs2(x,i):
    num2[x]=i
    for node in e2[x]:
        if num2[node]==0:dfs2(node,i)
cnt1=1
cnt2=1
for x in range(n):
    if num1[x]==0:dfs1(x,cnt1);cnt1+=1
    if num2[x]==0:dfs2(x,cnt2);cnt2+=1
dic={}
for x in range(n):
    t=(num1[x],num2[x])
    if t in dic:dic[t]+=1
    else:dic[t]=1
ans=[0]*n
for x in range(n):
    ans[x]=dic[(num1[x],num2[x])]
print ' '.join(map(str,ans))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

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

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self):
        return self.rank

n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
q1,q2=[],[]
ans=[0]*n
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
    q1.append((a-1,b-1))
    ans[a-1]=1
    ans[b-1]=1

for i in range(l):
    a,b=map(int,raw_input().split())
    uf2.unite(a-1,b-1)
    if ans[a-1]==0: ans[a-1]=1
    if ans[b-1]==0: ans[b-1]=1
    if uf.same(a-1,b-1):
        ans[a-1]=2
        ans[b-1]=2

uf2=UnionFind(n)
for i in q2:
    uf2.unite(i[0],i[1])
for i in q1:
    if uf2.find(i[[0],i[1]):
            ans[i[0]]=2
            ans[i[1]]=2
print ' '.join(map(str,ans))

Submission status: Runtime Error

Solution code:
# N K L
# p1 q1
# :
# pK qK
# r1 s1
# :
# rL sL
import numpy as np
N, K, L = map(int, raw_input().split())

# graph
Gp = dict()
Gq = dict()

# conn. components
p_con_todo = []
q_con_todo = []

# init
for n in range(1, N+1):
    p_con_todo.append(str(n))
    q_con_todo.append(str(n))
    Gp[str(n)] = []
    Gq[str(n)] = []
    
p_con_ids = np.zeros(N, dtype='int')
q_con_ids = np.zeros(N, dtype='int')

# input
for _ in range(K):
    p, q = map(int, raw_input().split())
    Gp[str(p)].append(str(q))
    Gp[str(q)].append(str(p))

for _ in range(L):
    p, q = map(int, raw_input().split())
    Gq[str(p)].append(str(q))
    Gq[str(q)].append(str(p))


    
# DFS
p_con_id = 0
while len(p_con_todo) > 0:
    p_con_id += 1
    ques = [p_con_todo[0]]
    conn = []
    while len(ques) > 0:
        n = ques.pop()
        conn.append(n)
        p_con_ids[int(n)-1] = p_con_id
        for m in Gp[n]:
            if m in conn:
                pass
            else:
                ques.append(m)
    p_con_todo = [n for n in p_con_todo if n not in conn]

# DFS
q_con_id = 0
while len(q_con_todo) > 0:
    q_con_id += 1
    ques = [q_con_todo[0]]
    conn = []
    while len(ques) > 0:
        n = ques.pop()
        conn.append(n)
        q_con_ids[int(n)-1] = q_con_id
        for m in Gq[n]:
            if m in conn:
                pass
            else:
                ques.append(m)
    q_con_todo = [n for n in q_con_todo if n not in conn]

# print p_con_ids
# print q_con_ids

# print anser
res_list = []
for n in range(N):
    res = int(np.ones(N)[p_con_ids = p_con_ids[n] and q_con_ids == q_con_ids[n]])
    res_list.append(str(res))
# print res_list
print " ".join(res_list)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.141592653589
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

class UnionFind:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

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

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self,x):
        return self.rank[x]


class UnionFind2:
    def __init__(self, size):
        self.rank=[0]*size
        self.par =range(size)
        self.grp =size

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

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

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する
        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する
        x,y=self.find(x),self.find(y)
        if x==y:
            return

        self.grp-=1
        if self.rank[x]<self.rank[y]:
            self.par[x]=y
        else:
            self.par[y]=x
            if self.rank[x]==self.rank[y]:
                self.rank[x]+=1

    def group_num(self):
        return self.grp
    def ra(self,x):
        return self.rank[x]



n,k,l=map(int,raw_input().split())
uf=UnionFind(n)
uf2=UnionFind2(n)
for i in range(k):
    a,b=map(int,raw_input().split())
    uf.unite(a-1,b-1)
for i in range(l):
    a,b=map(int,raw_input().split())
    uf2.unite(a-1,b-1)
ans=[]
for i in range(n):
    tmp=0
    if uf.rank(i):
        tmp+=1
    if uf2.rank(i):
        tmp+=1
    ans.append(tmp)
print ' '.join(map(str,ans))