Problem:


Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

4 4 1
2 1
1 3
3 2
3 4
4 1

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

5 10 0
1 2
1 3
1 4
1 5
3 2
2 4
2 5
4 3
5 3
4 5

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

10 9 3
10 1
6 7
8 2
2 5
8 4
7 3
10 9
6 4
5 8
2 6
7 5
3 1

Sample Output 3

1 3 5 4 3 3 3 3 1 0



Sample input:
4 4 1
2 1
1 3
3 2
3 4
4 1


Sample output:
0 1 0 1

Submission status: Time Limit Exceeded

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

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

u = UnionFind(n)

ans = [0 for i in range(n)]

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

for i in range(k):
    c, d = map(int, input().split())
    c -= 1
    d -= 1
    if u.same(c, d):
        ans[c] -= 1
        ans[d] -= 1


for y in u.all_group_members().values():
    x = len(y)
    for j in y:
        ans[j] += x - 1


print(" ".join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
from sys import setrecursionlimit
from collections import defaultdict
setrecursionlimit(100001)
n, m, k = map(int, input().split())
ab = []
cd = []
for _ in range(m):
    ab.append(list(map(int, input().split())))
for _ in range(k):
    cd.append(list(map(int, input().split())))
friendsof = defaultdict(list)
for a, b in ab:
    friendsof[a - 1].append(b - 1)
    friendsof[b - 1].append(a - 1)
enemiesof = defaultdict(list)
for c, d in cd:
    enemiesof[c - 1].append(d - 1)
    enemiesof[d - 1].append(c - 1)
canfrinums = []
def dps(i, output):
    output.append(i)
    for fr in friendsof[i]:
        if fr not in output:
            dps(fr, output)
canfris = [None] * n
for i in range(n):
    if canfris[i] == None:
        canfri_i = []
        dps(i, canfri_i)
        lencan = 0
        for x in canfri_i:
            if x != i and x not in friendsof[i] and x not in enemiesof[i]:
                lencan += 1
        for j in canfri_i:
            canfris[j] = canfri_i
        canfrinums.append(lencan)
    else:
        canfri_i = canfris[i]
        lencan = 0
        for x in canfri_i:
            if x != i and x not in friendsof[i] and x not in enemiesof[i]:
                lencan += 1
        canfrinums.append(lencan)
print(' '.join(map(str, canfrinums)))

Submission status: Time Limit Exceeded

Solution code:
import sys

n, m, k = map(int, sys.stdin.readline().split())
ab = [tuple(map(int, sys.stdin.readline().split())) for _ in range(m)]
cd = [tuple(map(int, sys.stdin.readline().split())) for _ in range(k)]
friend = [[] for _ in range(n+1)]
for a, b in ab:
    friend[a].append(b)
    friend[b].append(a)
block = [set() for _ in range(n+1)]
for c, d in cd:
    block[c].add(d)
    block[d].add(c)

root = list(range(n+1))
size = [1] * (n + 1)
height = [1] * (n + 1)

def find_root(u):
    v = root[u]
    if v == u:
        return u 
    w = find_root(v)
    root[u] = w 
    return w 

def unite(u, v):
    ru = find_root(u)
    rv = find_root(v)
    if ru != rv:
        if height[ru] >= height[rv]:
            root[rv] = ru 
            height[ru] = max(height[ru], height[rv] + 1)
            size[ru] += size[rv]
        else:
            root[ru] = rv 
            size[rv] += size[ru]

def main():
    for u in range(1, n+1):
        for v in friend[u]:
            unite(u, v)
    
    g = [set() for _ in range(n+1)]
    for i in range(1, n+1):
        g[find_root(i)].add(i)
    
    for i in range(1, n+1):
        yield len(g[root[i]] - block[i]) - len(friend[i]) - 1

if __name__ == '__main__':
    ans = main()
    print(*ans, sep=' ')

Submission status: Time Limit Exceeded

Solution code:
n, m, k = map(int, input().split())
p = [[[], []] for i in range(n)]
ans = []
for i in range(m):
    ai, bi = map(int, input().split())
    p[ai-1][0].append(bi-1)
    p[bi-1][0].append(ai-1)
for i in range(k):
    ci, di = map(int, input().split())
    p[ci-1][1].append(di-1)
    p[di-1][1].append(ci-1)
for i in range(n):
    stack = [i]
    depth = [0]
    already = []
    alreadyDepth = []
    cnt = 0
    while len(stack) != 0:
        now = stack.pop(0)
        nowDepth = depth.pop(0)
        already.append(now)
        alreadyDepth.append(nowDepth)
        if nowDepth >= 2 and not (now in p[i][0] or now in p[i][1]):
            cnt += 1
        for nextp in p[now][0]:
            if nextp in already or nextp in stack:
                continue
            stack.append(nextp)
            depth.append(nowDepth + 1)
    ans.append(cnt)
print(*ans)

Submission status: Time Limit Exceeded

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

class UnionFind(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]

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

tk=UnionFind(n)

kk=[[False] * n for _ in range(n)]

for _ in range(m):
    a,b=map(int, input().split())
    kk[a-1][b-1]=True
    kk[b-1][a-1]=True
    tk.union(a-1, b-1)

for _ in range(k):
    c,d=map(int, input().split())
    kk[c-1][d-1]=True
    kk[d-1][c-1]=True

for i in range(n):
    ans=-1
    for j in range(n):
        if not kk[i][j] and tk.is_same(i, j):
            ans+=1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
#####

import numpy as np
from numpy import newaxis, float32, float64, int32, int64, int16, int8, uint8, uint32, complex64, complex128
from collections import defaultdict

#####

def getIntList(inp):
	return [int(_) for _ in inp]
	

from sys import stdin

def getInputs():
	inputs=[]
	for line in stdin:
		line=line.split()
		inputs.append(line)
	return inputs


def st(x,y):
	return tuple(sorted([x,y]))

def getGroup(groups, i):
	if i not in groups:
		groups[i]=i
	return groups[i]
		
def main(inputs):
	n=int(inputs[0][0])
	m=int(inputs[0][1])
	k=int(inputs[0][2])

	fr=set()
	frSingle=defaultdict(set)
	for i in range(m):
		a=int(inputs[i+1][0])
		b=int(inputs[i+1][1])
		fr.add(st(a,b))
		frSingle[a].add(b)
		frSingle[b].add(a)
		
	bl=defaultdict(set)
	for i in range(k):
		a=int(inputs[i+1+m][0])
		b=int(inputs[i+1+m][1])
		bl[a].add(b)
		bl[b].add(a)
	
# 	print(fr)
# 	print(bl)
# 	print()
	
	groups=np.arange(n)+1
	members={}
	for i in range(1,n+1):
		members[i]=set([i])
	for i0,i1 in fr:
		g0=groups[i0-1]
		g1=groups[i1-1]
		if g0==g1:
			continue
		if g0<g1:
			mm=np.array(list(members[g1]))
			groups[mm-1]=g0
			members[g0].update(members[g1])
			members.pop(g1)
		else:
			mm=np.array(list(members[g0]))
			groups[mm-1]=g1
			members[g1].update(members[g0])
			members.pop(g0)
	
# 	print(groups)
# 	print(members)
	
# 	print()
	for i0 in range(1,n+1):
		g=groups[i0-1]
		i1s=set(members[g])
		i1s.remove(i0)
		i1s=i1s-frSingle[i0]
		i1s=i1s-bl[i0]
# 		print(i0,i1s)
		num=len(i1s)
		print(num, end="")
		if i0<n: print(" ", end="")
	
	

if __name__=="__main__":
	inputs=getInputs()
# 	inputs=simInputs()
	main(inputs)

Submission status: Time Limit Exceeded

Solution code:
import copy
N, M, K = map(int, input().split())
tomodachi  = [ [i] for i in range(N+1)]
for _ in range(M):
  a, b  = map(int, input().split())
  tomodachi[a].append(b)
  tomodachi[b].append(a)
dupli = copy.deepcopy(tomodachi)

for n in range(1, N+1):
  kouho = set()
  for friend in tomodachi[n]:
    if friend == n:
      continue
    else:
      kouho.add(friend)
  while kouho:
    f = kouho.pop()
    for g in tomodachi[f]:
      if g in tomodachi[n]:
        continue
      else:
        kouho.add(g)
        tomodachi[n].append(g)


for _ in range(K):
  c, d  = map(int, input().split())
  if c in tomodachi[d]:
    tomodachi[d].remove(c)
    tomodachi[c].remove(d)

ans = [ len(t)-len(s) for s, t in zip(dupli[1:], tomodachi[1:]) ]
print(' '.join(list(str(i) for i in ans)))

Submission status: Time Limit Exceeded

Solution code:

class UnionFind(object):
    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, exclude):
        root = self.find(x)
        return {i for i in range(self.n) if i not in exclude and 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):
        groups = {}
        for i in xrange(self.n):
            r = self.find(i)
            groups.setdefault(r, set()).add(i)
        return groups.values()


def main():
    n, m, k = map(int, raw_input().split())
    uf = UnionFind(n)
    ff = {i: {i} for i in xrange(n)}
    for _ in xrange(m):
        a, b = map(int, raw_input().split())
        a -= 1
        b -= 1
        ff[a].add(b)
        ff[b].add(a)
        uf.union(a, b)
    for _ in xrange(k):
        a, b = map(int, raw_input().split())
        a -= 1
        b -= 1
        ff[a].add(b)
        ff[b].add(a)

    # clusters = uf.all_group_members()
    ans = [0] * n
    for i in xrange(n):
        ans[i] = len(uf.members(i, ff[i]))
    print ' '.join(map(str, ans))

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
import queue
N, M, K = map(int,input().split())
ab = [tuple(map(int,input().split())) for _ in range(M)]
cd = [tuple(map(int,input().split())) for _ in range(K)]
dic = dd(list)
for (a,b) in ab:
    dic[str(a)].append(str(b))
    dic[str(b)].append(str(a))
seen = set()
def BFS(dic,node):
    cc = set()
    q = queue.Queue()
    q.put(node)
    cc.add(node)
    while not q.empty():
        now_node = q.get()
        cc.add(now_node)
        target = set(dic[now_node]) - cc
        for tgt in target:
            q.put(tgt)
    return cc
c_comp=[]
"""
for i in range(1,N+1):
    if str(i) not in seen:
        # 連結判定
        tmp = BFS(dic,str(i))
        seen = seen & set(tmp)
        c_comp.append(list(tmp))
"""
tg = set(range(1,N+1))
while len(tg)!=0:
    i = tg.pop()
    tmp = BFS(dic,str(i))
    seen = seen & set(tmp)
    c_comp.append(list(tmp))
    tg = tg - set(tmp)

uf = [0]*N
for i,ls in enumerate(c_comp):
    for val in ls:
        uf[int(val)-1] = i
for (a,b) in cd:
    if uf[a-1] == uf[b-1]:
        dic[str(a)].append(str(b))
        dic[str(b)].append(str(a))
res = [0]*N
for ls in c_comp:
    leng = len(ls)-1
    for idx in ls:
        res[int(idx)-1] = leng - len(dic[idx])
print(*res)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import sys

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

def main():
    n, m, k = map(int, read().split())
    friend, block = defaultdict(set), defaultdict(set)
    for _ in range(m):
        a, b = [int(i) - 1 for i in read().split()]
        friend[a].add(b)
        friend[b].add(a)
    for _ in range(k):
        c, d = [int(i) - 1 for i in read().split()]
        block[c].add(d)
        block[d].add(c)
    i = -1
    belonging = [-1] * n
    group = []
    next_search = []
    is_searched = [False] * n
    while not all(is_searched):
        if not next_search:
            for j, s in enumerate(is_searched):
                if not s:
                    next_search.append(j)
                    group.append(set())
                    i += 1
                    break
        j = next_search.pop()
        if is_searched[j]:
            continue
        is_searched[j] = True
        belonging[j] = i
        group[i].add(j)
        next_search += friend[j]
    suggestion = [len(group[belonging[i]].difference(friend[i]).difference(block[i])) - 1 for i in range(n)]
    print(*suggestion)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
input=sys.stdin.readline

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

P=[i for i in range(N+1)]
size=[1 for i in range(N+1)]

def find(a):
    if a==P[a]:
        return a
    else:
        return find(P[a])
        
def union(b,c):
    B=find(b)
    C=find(c)
    if size[C]>size[B]:
        P[B]=P[C]
    else:
        P[C]=P[B]
G=[0 for i in range(N+1)]
for i in range(M):
    a,b=map(int,input().split())
    G[a]+=1
    G[b]+=1
    union(a,b)
#print(P)
PP=[]
for i in range(N+1):
    PP.append(find(P[i]))
#print(PP)
PPP=[0 for i in range(N+1)]
for i in range(1,N+1):
    PPP[PP[i]]+=1
#print(PPP)

B=[[]for i in range(N+1)]
for i in range(K):
    c,d=map(int,input().split())
    B[c].append(d)
    B[d].append(c)
#print(G)
#print(B)
ans=[]
for i in range(1,N+1):
    ANS=PPP[PP[i]]-1-G[i]
    for j in B[i]:
        if PP[j]==PP[i]:
            ANS-=1
    ans.append(ANS)
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
input = sys.stdin.readline


N,M,K = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(M)]
CD = [list(map(int,input().split())) for _ in range(K)]

#%%
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 group_members(self):
        return [self.members(r) for r in self.roots()]
    
    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
#%%
uf = UnionFind(N)
for a,b in AB:
    uf.union(a-1,b-1)
    
ans = [0]*N

for group in uf.group_members():
    L = len(group)-1
    for a in group:
        ans[a] = L
        
# friends = [0]*N
# brock = [0]*N
for a,b in AB:
    ans[a-1] -= 1
    ans[b-1] -= 1

for c,d in CD:
    if uf.same(c-1,d-1):
        ans[c-1] -= 1
        ans[d-1] -= 1

print(*ans)

Submission status: Time Limit Exceeded

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

N, M, K = map(int, input().split())
F = [input().split() for i in range(M)]
bdict = {}
for i in range(K):
  a,b = map(int,input().split())
  a = a - 1
  b = b - 1
  if a not in bdict:
    bdict[a] = set()
  if b not in bdict:
    bdict[b] = set()
  bdict[a].add(b)
  bdict[b].add(a)
u = UnionFind(N)

fdict = {}
for f in F:
  a = int(f[0])-1
  b = int(f[1])-1
  u.union(a, b)
  if a not in fdict:
    fdict[a] = set()
  if b not in fdict:
    fdict[b] = set()
  fdict[a].add(b)
  fdict[b].add(a)
ans = ""
for i in range(N):
  mems = set(u.members(i))
  if i in bdict:
    mems = mems - bdict[i]
  if i in fdict:
    mems = mems - fdict[i]
  ans += str(len(mems) -1) + " "
print(ans[:-1])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
input = sys.stdin.readline


N,M,K = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(M)]
CD = [list(map(int,input().split())) for _ in range(K)]

#%%
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 group_members(self):
        return [self.members(r) for r in self.roots()]
    
    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
#%%
uf = UnionFind(N)
for a,b in AB:
    uf.union(a-1,b-1)
    
ans = [0]*N

for group in uf.group_members():
    L = len(group)-1
    for a in group:
        ans[a] = L
        
# friends = [0]*N
# brock = [0]*N
for a,b in AB:
    ans[a-1] -= 1
    ans[b-1] -= 1

for c,d in CD:
    if uf.same(c-1,d-1):
        ans[c-1] -= 1
        ans[d-1] -= 1

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N, M, K = (int(i) for i in input().split())
    fre = [set() for _ in range(N)]
    blo = [set() for _ in range(N)]
    mem = {i for i in range(N)}
    for i in range(M):
        a, b = (int(i) for i in input().split())
        fre[a-1].add(b-1)
        fre[b-1].add(a-1)
    for i in range(K):
        a, b = (int(i) for i in input().split())
        blo[a-1].add(b-1)
        blo[b-1].add(a-1)
    par = [i for i in range(N)]
    rank = [0 for i in range(N)]

    def find_root(x):
        if par[x] == x:
            return x
        else:
            par[x] = find_root(par[x])
            return par[x]

    def is_same_group(x, y):
        return find_root(x) == find_root(y)

    def unite(x, y):
        x = find_root(x)
        y = find_root(y)
        if x == y:
            return
        if rank[x] < rank[y]:
            par[x] = y
        else:
            par[y] = x
            if rank[x] == rank[y]:
                rank[x] += 1
    for i in range(N):
        for j in fre[i]:
            unite(i, j)
    for i in range(N):
        cur = 0
        for j in mem - fre[i] - {i} - blo[i]:
            if is_same_group(i, j):
                cur += 1
        print(cur, end=" ")
    print()


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
import queue
N, M, K = map(int,input().split())
ab = [tuple(map(int,input().split())) for _ in range(M)]
cd = [tuple(map(int,input().split())) for _ in range(K)]
dic = dd(list)
for (a,b) in ab:
    dic[str(a)].append(str(b))
    dic[str(b)].append(str(a))
seen = set()
def BFS(dic,node):
    cc = set()
    q = queue.Queue()
    q.put(node)
    cc.add(node)
    while not q.empty():
        now_node = q.get()
        cc.add(now_node)
        target = set(dic[now_node]) - cc
        for tgt in target:
            #if tgt not in cc:
            q.put(tgt)
            #seen.add(tgt)
    return cc
c_comp=[]
for i in range(1,N+1):
    if str(i) not in seen:
        # 連結判定
        tmp = BFS(dic,str(i))
        seen = seen & set(tmp)
        c_comp.append(list(tmp))
uf = [0]*N
for i,ls in enumerate(c_comp):
    for val in ls:
        uf[int(val)-1] = i
for (a,b) in cd:
    if uf[a-1] == uf[b-1]:
        dic[str(a)].append(str(b))
        dic[str(b)].append(str(a))
res = [0]*N
for ls in c_comp:
    leng = len(ls)-1
    for idx in ls:
        res[int(idx)-1] = leng - len(dic[idx])
print(*res)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from scipy.sparse.csgraph import connected_components
from scipy.sparse import lil_matrix

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

friend_mtx = lil_matrix((n, n))

friend_cnt = dict()
blocked_cnt = dict()

for i in range(m):
    a, b = map(int, input().split())
    friend_mtx[a-1, b-1] = 1
    friend_mtx[b-1, a-1] = 1
    if a-1 in friend_cnt:
        friend_cnt[a-1] = friend_cnt[a-1] + 1
    else:
        friend_cnt[a-1] = 1
    if b-1 in friend_cnt:
        friend_cnt[b-1] = friend_cnt[b-1] + 1
    else:
        friend_cnt[b-1] = 1

csr_mtx = friend_mtx.tocsr()
num, labels = connected_components(csr_mtx)

for i in range(k):
    c, d = map(int, input().split())
    if labels[c-1] == labels[d-1]:
        if c-1 in blocked_cnt:
            blocked_cnt[c-1] = blocked_cnt[c-1] + 1
        else:
            blocked_cnt[c-1] = 1
        if d-1 in blocked_cnt:
            blocked_cnt[d-1] = blocked_cnt[d-1] + 1
        else:
            blocked_cnt[d-1] = 1

renketsu_cnt = dict()

for item in labels:
    if item in renketsu_cnt:
        renketsu_cnt[item] = renketsu_cnt[item] + 1
    else:
        renketsu_cnt[item] = 1

for i in range(n):
    i_label = labels[i]
    renketsu_cnt_i = renketsu_cnt[i_label]
    num_friend = 0
    if i in friend_cnt:
        num_friend = friend_cnt[i]
    num_blocked = 0
    if i in blocked_cnt:
        num_blocked = blocked_cnt[i]
    print(renketsu_cnt_i - num_friend - num_blocked - 1, end="")
    if i != (n-1):
        print(' ', end="")
    else:
        print()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict, Counter


class UnionFind(object):
    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 main():
    n, m, k = list(map(int, sys.stdin.readline().strip().split()))

    friends = defaultdict(set)
    blocks = defaultdict(set)

    for i in range(m):
        a, b = list(map(int, sys.stdin.readline().strip().split()))
        a -= 1
        b -= 1
        friends[a].add(b)
        friends[b].add(a)

    for i in range(k):
        c, d = list(map(int, sys.stdin.readline().strip().split()))
        c -= 1
        d -= 1
        blocks[c].add(d)
        blocks[d].add(c)

    uf = UnionFind(n)

    for f_key in friends:
        for child in friends[f_key]:
            # child_cur_group = parents[child]
            uf.union(f_key, child)

    group_num_set = defaultdict(set)
    for i in range(n):
        group = uf.find(i)
        group_num_set[group].add(i)

    ans = [0] * n
    for i in range(n):
        group = uf.find(i)
        friend_cand = group_num_set[group]
        true_friend_cand = friend_cand.difference(blocks[i]).difference(friends[i])
        ans[i] = len(true_friend_cand) - 1

    return ans


result = main()
print(' '.join([str(num) for num in result]))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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


def main():
    N, M, K = [int(x) for x in input().split()]

    u = UnionFind(N)
    ans1 = [0] * N
    for _ in range(M):
        a, b = [int(x) for x in input().split()]
        ans1[a - 1] += 1
        ans1[b - 1] += 1
        u.union(a - 1, b - 1)

    ans2 = [0] * N
    for _ in range(K):
        a, b = [int(x) for x in input().split()]
        if u.same(a - 1, b - 1):
            ans2[a - 1] += 1
            ans2[b - 1] += 1

    for i in range(N):
        # friblo[i].add(i)
        # print(u.members(i))
        # print(friblo[i])
        # print(len(set(u.members(i)) - friblo[i]), end=" ")
        print(len(u.members(i)) - ans1[i] - ans2[i] - 1, end=" ")


if __name__ == '__main__':
    main()