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:
import unittest
import collections


class TestD(unittest.TestCase):
    def test_1(self):
        self.assertEqual(
            think(
                4,
                [
                    [2, 1],
                    [1, 3],
                    [3, 2],
                    [3, 4],
                ],
                [
                    [4, 1]
                ]
            ),
            [0, 1, 0, 1]
        )

    def test_2(self):
        self.assertEqual(
            think(
                5,
                [
                    [1, 2],
                    [1, 3],
                    [1, 4],
                    [1, 5],
                    [3, 2],
                    [2, 4],
                    [2, 5],
                    [4, 3],
                    [5, 3],
                    [4, 5],
                ],
                [
                ]
            ),
            [0, 0, 0, 0, 0]
        )

    def test_3(self):
        self.assertEqual(
            think(
                10,
                [
                    [10, 1],
                    [6, 7],
                    [8, 2],
                    [2, 5],
                    [8, 4],
                    [7, 3],
                    [10, 9],
                    [6, 4],
                    [5, 8],
                ],
                [
                    [2, 6],
                    [7, 5],
                    [3, 1],
                ]
            ),
            [1, 3, 5, 4, 3, 3, 3, 3, 1, 0]
        )


def solve():
    n, list_of_a_and_b, list_of_c_and_d = read()
    result = think(n, list_of_a_and_b, list_of_c_and_d)
    write(result)


def read():
    n, m, k = read_int(3)
    list_of_a_and_b = []
    for _ in range(m):
        a, b = read_int(2)
        list_of_a_and_b.append([a, b])
    list_of_c_and_d = []
    for _ in range(k):
        c, d = read_int(2)
        list_of_c_and_d.append([c, d])
    return n, list_of_a_and_b, list_of_c_and_d


def read_int(n):
    return read_type(int, n, sep=' ')


def read_float(n):
    return read_type(float, n, sep=' ')


def read_type(t, n, sep):
    return list(map(lambda x: t(x), read_line().split(sep)))[:n]


def read_line(n=0):
    if n == 0:
        return input().rstrip()
    else:
        return input().rstrip()[:n]


def think(n, list_of_a_and_b, list_of_c_and_d):
    adjacency_list_of_friend = make_adjacency_list_from(n, list_of_a_and_b)
    adjacency_list_of_block = make_adjacency_list_from(n, list_of_c_and_d)
    list_of_connected_graph = collect_connected_graph_from(n, adjacency_list_of_friend)
    candidate_of_friends = [0] * n
    for connected_graph in list_of_connected_graph:
        for vertex in connected_graph:
            index = vertex - 1
            candidate_of_friends[index] = len(connected_graph.difference(set(adjacency_list_of_block[vertex])))
            candidate_of_friends[index] -= len(adjacency_list_of_friend[vertex])
            candidate_of_friends[index] -= 1
    return candidate_of_friends


def write(result):
    print(' '.join(map(str, result)))


def make_adjacency_list_from(n, list_of_pair):
    adjacency_list = {}
    for i in range(1, n + 1):
        adjacency_list[i] = []
    for left, right in list_of_pair:
        adjacency_list[left].append(right)
        adjacency_list[right].append(left)
    return adjacency_list


def collect_connected_graph_from(n, adjacency_list):
    visited = [False for _ in range(n + 1)]
    list_of_connected_graph = []
    for vertex in range(1, len(visited)):
        if visited[vertex]:
            continue
        connected_graph = set([vertex])
        queue = collections.deque([vertex])
        while queue:
            data = queue.popleft()
            if visited[data]:
                continue
            visited[data] = True
            connected_graph.add(data)
            for next_data in adjacency_list[data]:
                queue.append(next_data)
        list_of_connected_graph.append(connected_graph)
    return list_of_connected_graph


if __name__ == '__main__':
    # unittest.main()
    solve()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import queue


def solve(inp):
    (N, M, K) = map(int, inp.readline().strip().split(' '))
    AB = [map(int, inp.readline().strip().split(' ')) for i in range(M)]
    CD = [map(int, inp.readline().strip().split(' ')) for i in range(K)]

    # Friend Graph
    A2B = [set() for i in range(N + 1)]
    for a, b in AB:
        A2B[a].add(b)
        A2B[b].add(a)
    # print('A2B=' + str(A2B))

    cl = [[] for i in range(N + 1)]
    visit = [False for i in range(N + 1)]
    for i in range(1, N + 1):
        if visit[i]:
            continue
        l = []
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            j = q.get()
            if visit[j]:
                continue
            l.append(j)
            visit[j] = True
            for k in A2B[j]:
                q.put(k)
        for j in l:
            cl[j] = l

    # Block Graph
    C2D = [set() for i in range(N + 1)]
    for c, d in CD:
        if d in cl[c]:
            C2D[c].add(d)
            C2D[d].add(c)
    # print('C2D=' + str(C2D))

    result = []
    for i in range(1, N + 1):
        r = len(cl[i]) - 1
        # - Friends
        r -= len(A2B[i])
        # - Blocks (in cluster)
        for j in C2D[i]:
            if j in cl[i]:
                r -= 1
        result.append(r)

    return " ".join(map(str, result))


def main():
    import sys
    result = solve(sys.stdin)
    if result is not None and result != '':
        print(result)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import queue


def solve(inp):
    (N, M, K) = map(int, inp.readline().strip().split(' '))
    AB = [map(int, inp.readline().strip().split(' ')) for i in range(M)]
    CD = [map(int, inp.readline().strip().split(' ')) for i in range(K)]

    # Friend Graph
    A2B = [set() for i in range(N + 1)]
    for a, b in AB:
        A2B[a].add(b)
        A2B[b].add(a)
    # Block Graph
    C2D = [set() for i in range(N + 1)]
    for c, d in CD:
        C2D[c].add(d)
        C2D[d].add(c)

    # print('A2B=' + str(A2B))
    # print('C2D=' + str(C2D))

    cl = [[] for i in range(N + 1)]
    visit = [False for i in range(N + 1)]
    for i in range(1, N + 1):
        if visit[i]:
            continue
        l = []
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            j = q.get()
            if visit[j]:
                continue
            l.append(j)
            visit[j] = True
            for k in A2B[j]:
                q.put(k)
        for j in l:
            cl[j] = l

    result = []
    for i in range(1, N + 1):
        r = len(cl[i]) - 1
        # - Friends
        r -= len(A2B[i])
        # - Blocks (in cluster)
        for j in C2D[i]:
            if j in cl[i]:
                r -= 1
        result.append(r)

    return " ".join(map(str, result))


def main():
    import sys
    result = solve(sys.stdin)
    if result is not None and result != '':
        print(result)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import queue


def solve(inp):
    (N, M, K) = map(int, inp.readline().strip().split(' '))
    AB = [map(int, inp.readline().strip().split(' ')) for i in range(M)]
    CD = [map(int, inp.readline().strip().split(' ')) for i in range(K)]

    # Friend Graph
    A2B = [set() for i in range(N + 1)]
    for a, b in AB:
        A2B[a].add(b)
        A2B[b].add(a)
    # Block Graph
    C2D = [set() for i in range(N + 1)]
    for c, d in CD:
        C2D[c].add(d)
        C2D[d].add(c)

    # print('A2B=' + str(A2B))
    # print('C2D=' + str(C2D))

    cl = [[] for i in range(N + 1)]
    r = [0 for i in range(N + 1)]
    visit = set()
    for i in range(1, N + 1):
        if i in visit:
            continue
        l = []
        q = queue.Queue()
        q.put(i)
        while not q.empty():
            j = q.get()
            if j in visit:
                continue
            l.append(j)
            visit.add(j)
            for k in A2B[j]:
                q.put(k)
        for j in l:
            cl[j] = l
            r[j] = len(l) - 1

    # - Friends
    for i in range(1, N + 1):
        r[i] -= len(A2B[i])

    # - Blocks (in cluster)
    for i in range(1, N + 1):
        for j in C2D[i]:
            if j in cl[i]:
                r[i] -= 1

    r.remove(0)
    return " ".join(map(str, r))


def main():
    import sys
    result = solve(sys.stdin)
    if result is not None and result != '':
        print(result)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,M,K=map(int,input().split())
fdic={}
for i in range(1,N+1):
  fdic[i]=set()  
for i in range(M):
  a,b=map(int,input().split())
  fdic[a].add(b)
  fdic[b].add(a)

bdic={}
for i in range(1,N+1):
  bdic[i]=set()
for i in range(K):
  c,d=map(int,input().split())
  bdic[c].add(d)
  bdic[d].add(c)
  
#print(fdic)
#print(bdic)

dic_cluster={}
cluster_num=0
cluster_list=[0]*(N+1)

for i in range(1,N+1):
  if cluster_list[i]>0:
    continue
  else:
    cluster_num+=1
    dic_cluster[cluster_num]=set()
    visited=set()
    queue=[i]
    while(len(queue)>0):
      new_queue=set()
      for q in queue:
        cluster_list[q]=cluster_num
        dic_cluster[cluster_num].add(q)
        visited.add(q)
        nx=fdic[q]
        for n in nx:
          if not n in visited:
            new_queue.add(n)

      queue=new_queue
      #print(new_queue)
      
#print(cluster_list)
#print(dic_cluster)

candlist=[]
for i in range(1,N+1):
  cluster_i=set(dic_cluster[cluster_list[i]])  
  #print(cluster_i.difference(fdic[i]).difference(bdic[i]))  
  candlist.append(str(len(cluster_i.difference(bdic[i]))-len(fdic[i])-1))
  
print(" ".join(candlist))

Submission status: Time Limit Exceeded

Solution code:
N,M,K=map(int,input().split())
fdic={}
for i in range(1,N+1):
  fdic[i]=set()  
for i in range(M):
  a,b=map(int,input().split())
  fdic[a].add(b)
  fdic[b].add(a)

bdic={}
for i in range(1,N+1):
  bdic[i]=set()
for i in range(K):
  c,d=map(int,input().split())
  bdic[c].add(d)
  bdic[d].add(c)
  
#print(fdic)
#print(bdic)

dic_cluster={}
cluster_num=0
cluster_list=[0]*(N+1)

for i in range(1,N+1):
  if cluster_list[i]>0:
    continue
  else:
    cluster_num+=1
    dic_cluster[cluster_num]=set()
    visited=set()
    queue=[i]
    while(len(queue)>0):
      new_queue=set()
      for q in queue:
        cluster_list[q]=cluster_num
        dic_cluster[cluster_num].add(q)
        visited.add(q)
        nx=fdic[q]
        for n in nx:
          if not n in visited:
            new_queue.add(n)

      queue=new_queue
      #print(new_queue)
      
#print(cluster_list)
#print(dic_cluster)

candlist=[]
for i in range(1,N+1):
  cluster_i=set(dic_cluster[cluster_list[i]])  
  cluster_i.remove(i)
  #print(cluster_i.difference(fdic[i]).difference(bdic[i]))  
  candlist.append(str(len(cluster_i.difference(fdic[i]).difference(bdic[i]))))
  
print(" ".join(candlist))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007
"""
#N,K,Mが入力
    n,k,m=LI() 
    #N
    #x1 y1
    #.  .
    #xn ynが入力
    N=I()
    p=LIR(N)
    print(n,k,m,p)
"""

############################## ユニオン木(union tree) ###################################
#uf=UnionFind(n)と使う
# print(uf.roots())
# print(uf.all_group_members())
class UnionFind:
    def __init__(self, n):
        self.n=n
        self.par = [-1 for i in range(self.n+1)]
        self.rank = [0 for i in range(self.n+1)]#素集合でないとrankは意味がなさそう,素集合であればrank kには少なくとも2^k要素がある。
    
    # 検索
    def find(self, x):
        # if self.par[x] == x:
        if self.par[x] <0:
            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[y]+=self.par[x]
            self.par[x] = y
        else:
            self.par[x]+=self.par[y]
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
        
    # 同じ集合に属するか判定
    def same(self, x, y):
        return self.find(x) == self.find(y)

    #要素xが属するグループに属する要素をリストで返す
    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n+1) if self.find(i) == root]

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

    #すべての根の要素をリストで返す
    def roots(self):
        return [i for i, x in enumerate(self.par) if x<0]

    #グループの数を返す
    def group_count(self):
        return len(self.roots())

    #{ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す
    def all_group_members(self):
        return {int(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 resolve():
    n,m,k=LI()
    A=LIR(m)
    C=LIR(k)

    uf=UnionFind(n-1)
    # ub=UnionFind(n-1)
    dame=[[] for i in range(n)]
    for i in range(m):
        a=A[i][0]-1
        b=A[i][1]-1
        dame[a].append(b)
        dame[b].append(a)
        uf.union(a,b)

    for i in range(k):
        c=C[i][0]-1
        d=C[i][1]-1
        if uf.same(c,d)==True:
            dame[c].append(d)
            dame[d].append(c)
        # ub.union(c,d)

    # d=uf.all_group_members()
    # print(d)
    ans=""
    for i in range(n):
        ans+=str((uf.size(i)-1-len(dame[i])))+" "
    print(ans)
import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """4 4 1
2 1
1 3
3 2
3 4
4 1"""
        output = """0 1 0 1"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """5 10 0
1 2
1 3
1 4
1 5
3 2
2 4
2 5
4 3
5 3
4 5"""
        output = """0 0 0 0 0"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """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"""
        output = """1 3 5 4 3 3 3 3 1 0"""
        self.assertIO(input, output)

if __name__ == "__main__":
    #unittest.main()
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import queue

N,M,K=map(int,input().split())
friend=[[] for i in range(N)]
block=[[] for i in range(N)]
color=[-1]*N
c=0
for i in range(M):
    a,b=map(int,input().split())
    friend[a-1].append(b-1)
    friend[b-1].append(a-1)
for i in range(K):
    c,d=map(int,input().split())
    block[c-1].append(d-1)
    block[d-1].append(c-1)

q=queue.Queue()

for i in range(N):
    if color[i]==-1:
        q.put(i)
        color[i]=c
        while not q.empty():
            s=q.get()
            for t in friend[s]:
                if color[t]==-1:
                    color[t]=c
                    q.put(t)
        c+=1

count=[0]*c

for i in range(c):
    count[i]=color.count(i)

for i in range(N):
    block_in_color=0
    for t in block[i]:
        if color[i]==color[t]:
            block_in_color+=1
    print(count[color[i]]-len(friend[i])-block_in_color-1)

Submission status: Time Limit Exceeded

Solution code:
class uf():

    def __init__(self,n):
        self.size=n
        self.parents=list(range(n))

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

    def union(self,a,b):
        x=self.find(a)
        y=self.find(b)
        if x==y:
            return
        if x>y:
            x,y=y,x
        self.parents[y]=x

    def groupmembers(self,x):
        r=self.find(x)
        return {y for y in list(range(r,self.size)) if self.find(y)==r}


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

f=[]
for c in range(m):
    f.append([int(x)-1 for x in input().split()])

b=[]
for c in range(k):
    b.append([int(x)-1 for x in input().split()])

s=uf(n)
for c in range(m):
    s.union(f[c][0],f[c][1])

g=[set() for x in range(n)]
for c in range(m):
    p=f[c][0]
    q=f[c][1]
    g[p].add(q)
    g[q].add(p)
for c in range(k):
    p=b[c][0]
    q=b[c][1]
    g[p].add(q)
    g[q].add(p)

a=[]
for c in range(n):
    t=s.groupmembers(c)
    u=t-g[c]
    a.append(str(len(u)-1))

print(" ".join(a))

Submission status: Time Limit Exceeded

Solution code:
import itertools

base = list(map(int, input().split(' ')))
N=base[0]
M=base[1]
K=base[2]
terms=[]
for i in range(N):
  term=[]
  for j in range(N):
    term+=[[i,j,0]]
  terms+=[term]
for i in range(M):
  term=list(map(int, input().split(' ')))
  terms[term[0]-1][term[1]-1][2]=1
  terms[term[1]-1][term[0]-1][2]=1
for i in range(K):
  term=list(map(int, input().split(' ')))
  terms[term[0]-1][term[1]-1][2]=-1
  terms[term[1]-1][term[0]-1][2]=-1
for i in range(N):
  for j in range(i+1,N):
    counter=0
    if terms[i][j][2]==0 and i!=j:
      sample=[]
      test=[]
      for l in range(N):
        sample+=[l]
      sample.remove(i)
      sample.remove(j)
      
      for l in range(1,N-1):
        test+=list(itertools.permutations(sample,l))
      for l in range(len(test)):
        tester=test[l]
        score=terms[i][tester[0]][2]
        count=1
        for m in range(0,len(tester)-1):
          score+=terms[tester[m]][tester[m+1]][2]
          count+=1
        score+=terms[tester[len(tester)-1]][j][2]  
        count+=1
        if count==score:
          counter=1
          break
    terms[i][i][2]+=counter
    terms[j][j][2]+=counter

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

Submission status: Time Limit Exceeded

Solution code:
import collections
n,m,k=map(int,input().split())
a=[list(map(int,input().split())) for i in range(m)]
c=[list(map(int,input().split())) for i in range(k)]

l=[i for i in range(1,n+1)] #根
ll=[1 for i in range(n)] #長さ
for i in range(m):
    p=a[i][0]
    q=a[i][1]

    li=[p]
    while l[p-1]!=p:
        p=l[p-1]
        li.append(p)
    for j in li:
        l[j-1]=p

    li=[]
    while l[q-1]!=q:
        q=l[q-1]
        li.append(q)
    for j in li:
        l[j-1]=q

    if p!=q:
        if ll[p-1]==ll[q-1]:
            ll[p-1]+=1
            l[q-1]=p
        elif ll[p-1]>ll[q-1]:
            l[q-1]=p
        else:
            l[p-1]=q

for i in range(n):
    p=i
    while l[p-1]!=p:
        p=l[p-1]
    l[i-1]=p

lm=[]
for i in range(n):
    b=collections.Counter(l)
    lm.append(b[l[i]]-1)

for i in range(m):
    if l[a[i][0]-1]==l[a[i][1]-1]:
        lm[a[i][0]-1]-=1
        lm[a[i][1]-1]-=1
for i in range(k):
    if l[c[i][0]-1]==l[c[i][1]-1]:
        lm[c[i][0]-1]-=1
        lm[c[i][1]-1]-=1

print(*lm)

Submission status: Time Limit Exceeded

Solution code:
n,m,k = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(m)]
cd = [list(map(int, input().split())) for _ in range(k)]

f1 = [set() for _ in range(0, n+1)]
b1 = [set() for _ in range(0, n+1)]
fb1 = [set() for _ in range(0, n+1)]
ans = [0]*(n+1)

for x,y in ab:
    f1[x].add(y)
    f1[y].add(x)
    fb1[x].add(y)
    fb1[y].add(x)

for x,y in cd:
    b1[x].add(y)
    b1[y].add(x)
    fb1[x].add(y)
    fb1[y].add(x)

v0 = []
all_v = []
for h in range(1, n+1):
    if h in all_v:
        continue
    st1 = [h]
    v1 = set()
    while st1:
        take1 = st1.pop()
        v1.add(take1)
        for i in f1[take1]:
            if i in v1:
                continue
            if i in st1:
                continue
            st1.append(i)
    v0.append(v1)
    all_v += v1

for i in v0:
    leni = len(i)
    for j in i:
        ans[j] = leni - len(i & fb1[j]) - 1

print(*ans[1:])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
class UnionFind():
    def __init__(self, n):
        self.n = n+1
        self.parents = [-1] * (n+1)

    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 = list(map(int, input().split()))
friend = [set() for i in range(n+1)]
tree = UnionFind(n)
for i in range(m):
    a, b = map(int, input().split())
    friend[a].add(b)
    friend[b].add(a)
    tree.union(a, b)

for i in range(k):
    c, d = map(int, input().split())
    friend[c].add(d)
    friend[d].add(c)

ans = [0]*(n+1)
for group in tree.all_group_members().values():
    group = set(group)
    for elem in group:
        ans[elem] = len(group - friend[elem])-1

print(" ".join(map(str, ans[1:])))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
class Union_Find():
    def __init__(self, num):
        self.par = [-1]*(num+1)
        self.siz = [1]*(num+1)

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

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

    def union(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if rx != ry:
            if self.par[rx] < self.par[ry]:
                self.par[ry] = rx
                self.siz[rx] += self.siz[ry]
            elif self.par[rx] > self.par[ry]:
                self.par[rx] = ry
                self.siz[ry] += self.siz[rx]
            else:
                self.par[rx] -= 1
                self.par[ry] = rx
                self.siz[rx] += self.siz[ry]
        return

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

n, m, k = list(map(int, input().split()))
friend = [set() for i in range(n+1)]
block = [set() for i in range(n+1)]
tree = Union_Find(n)
for i in range(m):
    a, b = map(int, input().split())
    friend[a].add(b)
    friend[b].add(a)
    tree.union(a, b)

for i in range(k):
    c, d = map(int, input().split())
    block[c].add(d)
    block[d].add(c)

ans = []
for i in range(1, n+1):
    tree.find(i)

friend_list = [set() for i in range(n+1)]
tree_find = [tree.find(i) for i in range(1, n+1)]
for i in range(1, n+1):
    friend_list[tree_find[i-1]].add(i)
for i in range(1, n+1):
    ans.append(len(friend_list[tree_find[i-1]] - friend[i] - block[i])-1)

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, M, K = map(int, input().split())
A = [0]*M
B = [0]*M
for i in range(M):
    A[i], B[i] = map(int, input().split())
C = [0]*K
D = [0]*K
for i in range(K):
    C[i], D[i] = map(int,input().split())

friend = {i: set([]) for i in range(1, N+1)}
brock = {i: set([]) for i in range(1, N+1)}
for i in range(M):
    friend[A[i]].add(B[i])
    friend[B[i]].add(A[i])
for i in range(K):
    brock[C[i]].add(D[i])
    brock[D[i]].add(C[i])

labels = [0] * (N+1)


def mark(n, label):
    if labels[n] != 0:
        return -1
    else:
        q = deque()
        q.append(n)
        labels[n] = label
        while q != deque():
            node = q.pop()
            labels[node] = label
            for i in friend[node]:
                if labels[i] == 0:
                    q.append(i)
        return label


label = 1
for n in range(1, N + 1):
    if mark(n, label) != -1:
        label += 1

group_size = [0] * label
for l in range(1, len(group_size)):
    group_size[l] = labels.count(l)

res = [0] * N
for n in range(1, N + 1):
    tmp = 0
    for b in brock[n]:
        if labels[n] == labels[b]:
            tmp += 1
    res[n - 1] = group_size[labels[n]] - 1 - len(friend[n]) - tmp

print(*res)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
class Union_Find():
    def __init__(self, num):
        self.par = [-1]*(num+1)
        self.siz = [1]*(num+1)

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

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

    def union(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if rx != ry:
            if self.par[rx] < self.par[ry]:
                self.par[ry] = rx
                self.siz[rx] += self.siz[ry]
            elif self.par[rx] > self.par[ry]:
                self.par[rx] = ry
                self.siz[ry] += self.siz[rx]
            else:
                self.par[rx] -= 1
                self.par[ry] = rx
                self.siz[rx] += self.siz[ry]
        return

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

n, m, k = list(map(int, input().split()))
friend = [set() for i in range(n+1)]
block = [set() for i in range(n+1)]
tree = Union_Find(n)
for i in range(m):
    a, b = map(int, input().split())
    friend[a].add(b)
    friend[b].add(a)
    tree.union(a, b)

for i in range(k):
    c, d = map(int, input().split())
    block[c].add(d)
    block[d].add(c)

ans = []
for i in range(1, n+1):
    tree.find(i)

friend_list = [set() for i in range(2*n+1)]
for i in range(1, n+1):
    friend_list[tree.find(i)].add(i)
for i in range(1, n+1):
    group = friend_list[tree.find(i)]
    group = group - friend[i] - block[i]
    ans.append(len(group)-1)
    
print(" ".join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, M, K = map(int, input().split())
A = [0]*M
B = [0]*M
for i in range(M):
    A[i], B[i] = map(int,input().split())
C = [0]*K
D = [0]*K
for i in range(K):
    C[i], D[i] = map(int,input().split())

friend = {i: set([]) for i in range(1, N+1)}
brock = {i: set([]) for i in range(1, N+1)}
for i in range(M):
    friend[A[i]].add(B[i])
    friend[B[i]].add(A[i])
for i in range(K):
    brock[C[i]].add(D[i])
    brock[D[i]].add(C[i])

labels = [0] * (N+1)


def mark(n, label):
    if labels[n] != 0:
        return -1
    else:
        q = deque()
        q.append(n)
        labels[n] = label
        while q != deque():
            node = q.pop()
            labels[node] = label
            for i in friend[node]:
                if labels[i] == 0:
                    q.append(i)
        return label


label = 1
for n in range(1, N + 1):
    if mark(n, label) != -1:
        label += 1

group_size = [0] * label
for l in range(1, len(group_size)):
    group_size[l] = len([i for i in labels if i == l])

res = [0] * N
for n in range(1, N + 1):
    tmp = 0
    for b in brock[n]:
        if labels[n] == labels[b]:
            tmp += 1
    res[n - 1] = group_size[labels[n]] - 1 - len(friend[n]) - tmp

print(*res)

Submission status: Time Limit Exceeded

Solution code:

n,m,k = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(m)]
cd = [list(map(int, input().split())) for _ in range(k)]

g1 = {}
for i in range(1, n+1): g1[i] = []

ans = [0]*n
for x,y in ab:
    g1[x] += [y]
    g1[y] += [x]
    ans[x-1] -= 1
    ans[y-1] -= 1

v0 = []
all_v = []
for h in range(1, n+1):
    if h in all_v:
        continue
    st1 = [h]
    v1 = []
    while st1:
        take1 = st1.pop()
        v1.append(take1)
        for i in g1[take1]:
            if i in v1:
                continue
            if i in st1:
                continue
            st1.append(i)
    v0.append(v1)
    all_v += v1

cc1 = [-1]*n
for ii,i in enumerate(v0):
    l1 = len(i) -1
    for j in i:
        ans[j-1] += l1
        cc1[j-1] = ii

for x,y in cd:
    if cc1[x-1] == cc1[y-1]:
        ans[x-1] -= 1
        ans[y-1] -= 1

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