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: Accepted

Solution code:
N, M, K = list(map(int, input().split()))
p = [0] * N # p[][0] 友達リスト　p[][1] ブロックリスト p[][2] 所属グループ(-1はなし)
for i in range(N):
    p[i] = [0]*3
    p[i][0] = []
    p[i][1] = []
    p[i][2] = -1
g = [] # グループのサイズ
stack = []
groupNum = 0
fcs = []

for i in range(M):
    a, b = list(map(int, input().split()))
    p[a-1][0].append(b-1)
    p[b-1][0].append(a-1)

def groupmake(person,group):
    groupSize = 0
    stack.append(person)
    p[person][2] = group
    while True:
        num = stack.pop()
        groupSize += 1
        for i in p[num][0]:
            if p[i][2] == -1:
                stack.append(i)
                p[i][2] = group
        if len(stack) == 0:
            return groupSize

for i in range(len(p)):
    if p[i][2] == -1:
        g.append(groupmake(i, groupNum))
        groupNum += 1

for person in p:
    fcs.append(g[person[2]] - len(person[0]) -1)

for i in range(K):
    c, d = list(map(int, input().split()))
    if p[c-1][2] == p[d-1][2]:
        fcs[c-1] -= 1
        fcs[d-1] -= 1

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

Submission status: Accepted

Solution code:
import collections

n, m, k = map(int, input().split())
ab = [[] for i in range(n + 1)]
cd = [[] for i in range(n + 1)]
for i in range(m):
    a, b = map(int, input().split())
    ab[a].append(b)
    ab[b].append(a)
for i in range(k):
    c, d = map(int, input().split())
    cd[c].append(d)
    cd[d].append(c)
flag = [False for i in range(n + 1)]
groups = []
num = 1
while num <= n:
    if flag[num] == True:
        num += 1
        continue
    else:
        temp = set()
        queue = collections.deque([num])
        while queue:
            temp2 = queue.popleft()
            temp |= {temp2}
            flag[temp2] = True
            for i in ab[temp2]:
                if i not in temp:
                    queue.append(i)
        groups.append(temp)
group = [None for i in range(n + 1)]
for i in range(len(groups)):
    for j in groups[i]:
        group[j] = i
for i in range(1, n + 1):
    temp = groups[group[i]]
    temp2 = temp & set(cd[i])
    temp3 = temp & set(ab[i])
    print(len(temp) - 1 - len(temp2) - len(temp3), end = " ")

Submission status: Accepted

Solution code:
class UnionFind:
    def __init__(self, n: int) -> None:
        self.forest = [-1] * n

    def union(self, x: int, y: int) -> None:
        x = self.findRoot(x)
        y = self.findRoot(y)
        if x == y:
            return
        if self.forest[x] > self.forest[y]:
            x, y = y, x
        self.forest[x] += self.forest[y]
        self.forest[y] = x
        return

    def findRoot(self, x: int) -> int:
        if self.forest[x] < 0:
            return x
        else:
            self.forest[x] = self.findRoot(self.forest[x])
            return self.forest[x]

    def issame(self, x: int, y: int) -> bool:
        return self.findRoot(x) == self.findRoot(y)

    def size(self, x: int) -> int:
        return -self.forest[self.findRoot(x)]


n, m, k = map(int, input().split())
u = UnionFind(n)
dire = [[] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    dire[a - 1].append(b - 1)
    dire[b - 1].append(a - 1)
    u.union(a - 1, b - 1)
for i in range(k):
    c, d = map(int, input().split())
    if u.issame(c-1,d-1):
        dire[c - 1].append(d - 1)
        dire[d - 1].append(c - 1)

print(*[u.size(i) - len(dire[i]) - 1 for i in range(n)])

Submission status: Accepted

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

friends = [set() for _ in range(N)]
for _ in range(M):
    a,b = map(lambda x: int(x)-1, input().split())
    friends[a].add(b)
    friends[b].add(a)

blocks = [set() for _ in range(N)]
for _ in range(K):
    c,d = map(lambda x: int(x)-1, input().split())
    blocks[c].add(d)
    blocks[d].add(c)

ans = [0]*N
visited = [False]*N
for i in range(N):
    if visited[i]:
        continue
    visited[i] = True
    d = [i]
    check = {i} 
    while len(d):
        tmp = d.pop()
        for k in friends[tmp]:
            if visited[k]:
                continue
            d.append(k)
            visited[k] = True
            check.add(k)
    for j in check:
        ans[j] += len(check) - len(friends[j]&check) - len(blocks[j]&check) - 1
print(*ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

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)]

ff = [[] for _ in range(n+1)]
for a, b in ab:
    ff[a].append(b)
    ff[b].append(a)

visited = [False] * (n+1)
visited[0] = True

com = [-1] * (n+1)


def dfs(v, ff, visited, com, g):
    q = deque([v])
    visited[v] = True
    com[v] = g
    k = 1
    while len(q) > 0:
        w = q.pop()
        for x in ff[w]:
            if not visited[x]:
                q.append(x)
                visited[x] = True
                com[x] = g
                k += 1
    return k

g = 0
group_num = []

for i in range(1, n+1):
    if visited[i]:
        pass
    else:
        k = dfs(i, ff, visited, com, g)
        group_num.append(k)
        g += 1

#print(com)

friends = [0] * (n+1)

for i in range(1, n+1):
    friends[i] += group_num[com[i]] - 1

for a, b in ab:
    if com[a] == com[b]:
        friends[a] -= 1
        friends[b] -= 1

for c, d in cd:
    if com[c] == com[d]:
        friends[c] -= 1
        friends[d] -= 1

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

Submission status: Accepted

Solution code:
class UnionFind:
    def __init__(self, numV):
        self.pars = list(range(numV))
        self.ranks = [0] * numV
        self.sizes = [1] * numV
    def getRoot(self, x):
        par = self.pars[x]
        if par != x:
            self.pars[x] = par = self.getRoot(par)
        return par
    def merge(self, x, y):
        x, y = self.getRoot(x), self.getRoot(y)
        sx, sy = self.sizes[x], self.sizes[y]
        if x == y: return (0, 0)
        if self.ranks[x] < self.ranks[y]:
            self.pars[x] = y
            self.sizes[y] += sx
        else:
            self.pars[y] = x
            self.sizes[x] += sy
            if self.ranks[x] == self.ranks[y]:
                self.ranks[x] += 1
        return (sx, sy)
    def isSame(self, x, y):
        return self.getRoot(x) == self.getRoot(y)
    def updatePars(self):
        for v in range(len(self.pars)):
            self.getRoot(v)
    def getSize(self, x):
        return self.sizes[self.getRoot(x)]

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

uf = UnionFind(n)
ex = [[] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    uf.merge(a,b)
    ex[a].append(b)
    ex[b].append(a)

for i in range(k):
    c, d = map(int, input().split())
    c -= 1
    d -= 1
    if uf.getRoot(c) == uf.getRoot(d):
        ex[c].append(d)
        ex[d].append(c)


ans = []
for i in range(n):
    r = uf.getRoot(i)
    ans.append(uf.sizes[r] - len(list(set(ex[i]))) - 1)
ans = [str(i) for i in ans]
print(' '.join(ans))

Submission status: Accepted

Solution code:
from collections import defaultdict


class DisjoinSet:
    def __init__(self, N):
        self.par = [-1] * N
        self.sz = [1] * N

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

    def unite(self, a, b):
        a = self.root(a)
        b = self.root(b)
        if a == b:
            return
        if self.sz[a] > self.sz[b]:
            a, b = b, a
        self.par[a] = b
        self.sz[b] += self.sz[a]

    def same(self, a, b):
        return self.root(a) == self.root(b)

    def size(self, x):
        return self.sz[self.root(x)]

    def __str__(self):
        clusters = defaultdict(list)
        for x in range(N):
            clusters[self.root(x)].append(x)
        return str(list(clusters.values()))


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

A, B = [], []
for _ in range(M):
    a, b = map(int, input().split())
    A.append(a - 1)
    B.append(b - 1)

C, D = [], []
for _ in range(K):
    c, d = map(int, input().split())
    C.append(c - 1)
    D.append(d - 1)

data = DisjoinSet(N)
for a, b in zip(A, B):
    data.unite(a, b)

ans = [data.size(x) - 1 for x in range(N)]

for a, b in zip(A, B):
    ans[a] -= 1
    ans[b] -= 1

for c, d in zip(C, D):
    if data.same(c, d):
        ans[c] -= 1
        ans[d] -= 1

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

class UnionFindPathCompression():
    def __init__(self, n):
        self.parents = list(range(n))
        self.rank = [1]*n
        self.group_size = [1]*n

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

    def union(self, x, y):
        #親を探す p = parentの意味
        px = self.find(x)
        py = self.find(y)

        if px == py:
            return
        else:
            if self.rank[px] < self.rank[py]:
                self.parents[px] = py
                self.group_size[py] += self.group_size[px]
            else:
                self.parents[py] = px
                self.group_size[px] += self.group_size[py]
                #ランクの更新
                if self.rank[px] == self.rank[py]:
                    self.rank[px] += 1
                
n,m,k = map(int,input().split())
ufpc = UnionFindPathCompression(n)
friends = [[] for i in range(n)]
ans = [-1]*n
for i in range(m):
    a, b = (int(x) for x in input().split())
    a, b = a-1, b-1
    friends[a].append(b)
    friends[b].append(a)
    ufpc.union(a,b)

for i in range(k):
    c, d = (int(x) for x in input().split())
    c, d = c-1, d-1
    if ufpc.find(c) == ufpc.find(d):
        ans[c] -= 1
        ans[d] -= 1

for i in range(n):
    ans[i] += ufpc.group_size[ufpc.find(i)]
    ans[i] -= len(friends[i])

print(*ans)

Submission status: Accepted

Solution code:

# count the size of the component to which a node belongs to 
# subtract all the direct friendship and direct blockships
# subtract 1 itself
import sys
import os
sys.setrecursionlimit(1000000)
from collections import defaultdict
adj = defaultdict(list)
adj1=defaultdict(list)
szc = [ 0 for i in range(300000)]
which =[0 for i in range(300000)]
vis = [0 for i in range(300000)]
tot =0
def dfs1(u):
	global tot
	vis[u]=1
	which[u]=tot
	szc[tot]=szc[tot]+1
	for i in adj[u]:
		if vis[i]==1:
			continue
		dfs1(i)
def main():
	global tot
	n , m , k = map(int, input().split())
	bk =[0 for i in range(n+1)]
	fd =[0 for i in range(n+1)]
	for i in range(m):
		x, y = map(int ,input().split())
		adj[x].append(y)
		adj[y].append(x)
		fd[x]=fd[x]+1
		fd[y]=fd[y]+1
	for i in range(k):
		x, y = map(int , input().split())
		adj1[x].append(y)
		adj1[y].append(x)
	for i in range(1, n+1):
		if vis[i]!=1:
			tot = tot+1
			dfs1(i)
	ans=[]
	for i in range(1, n+1):
		res = szc[which[i]]
		res = res-fd[i]
		res = res-1
		for j in adj1[i]:
			if which[j]==which[i]:
				res =res -1
		ans.append(res)
	print(*ans)
		
if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
import sys
import os
sys.setrecursionlimit(1000000)
from collections import defaultdict
adj = defaultdict(list)
adj1=defaultdict(list)
szc = [ 0 for i in range(300000)]
which =[0 for i in range(300000)]
vis = [0 for i in range(300000)]
tot =0
def dfs1(u):
	global tot
	vis[u]=1
	which[u]=tot
	szc[tot]=szc[tot]+1
	for i in adj[u]:
		if vis[i]==1:
			continue
		dfs1(i)
def main():
	global tot
	n , m , k = map(int, input().split())
	bk =[0 for i in range(n+1)]
	fd =[0 for i in range(n+1)]
	for i in range(m):
		x, y = map(int ,input().split())
		adj[x].append(y)
		adj[y].append(x)
		fd[x]=fd[x]+1
		fd[y]=fd[y]+1
	for i in range(k):
		x, y = map(int , input().split())
		adj1[x].append(y)
		adj1[y].append(x)
	for i in range(1, n+1):
		if vis[i]!=1:
			tot = tot+1
			dfs1(i)
	ans=[]
	for i in range(1, n+1):
		res = szc[which[i]]
		res = res-fd[i]
		res = res-1
		for j in adj1[i]:
			if which[j]==which[i]:
				res =res -1
		ans.append(res)
	print(*ans)
		
if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:

class UnionFind:
    def __init__(self, n):
        self.par = list(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 unite(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        elif self.rank[x] < self.rank[y]:
            x, y = y, x

        self.par[y] = x
        self.size[x] += self.size[y]

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

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


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

friend = [[] for _ in range(N + 1)]
for a, b in X:
    friend[a].append(b)
    friend[b].append(a)

blocked = [[] for _ in range(N + 1)]
for c, d in X:
    blocked[c].append(d)
    blocked[d].append(c)

tree = UnionFind(N + 1)
for a, b in X:
    tree.unite(a, b)

ans = [0] * (N + 1)
for i in range(1, N + 1):
    ans[i] = tree.get_size(i) - len(friend[i]) - 1

for c, d in Y:
    if tree.is_same(c, d):
        ans[c] -= 1
        ans[d] -= 1

print(*ans[1:])

Submission status: Accepted

Solution code:


class DisjointSet:

    def __init__(self, N):
        self.parents = [i for i in range(N)]
        self.size = [1]*N

    def find_parent(self, x):
        path = []
        while self.parents[x] != x:
            x = self.parents[x]
            path.append(x)
        for p in path:
            self.parents[p] = x
        return x

    def find_size(self, x):
        return self.size[self.find_parent(x)]

    def union(self, x, y):
        root_x = self.find_parent(x)
        root_y = self.find_parent(y)
        if self.find_parent(root_x) != self.find_parent(root_y):
            self.parents[root_x] = root_y
            self.size[root_y] += self.size[root_x]


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N, M, K = read_ints()
    disjoint_set = DisjointSet(N)
    suggestions = [-1]*N
    for _ in range(M):
        a, b = read_ints()
        a -= 1
        b -= 1
        disjoint_set.union(a, b)
        suggestions[a] -= 1
        suggestions[b] -= 1
    for _ in range(K):
        c, d = read_ints()
        c -= 1
        d -= 1
        if disjoint_set.find_parent(c) == disjoint_set.find_parent(d):
            suggestions[c] -= 1
            suggestions[d] -= 1
    return [disjoint_set.find_size(i)+suggestions[i] for i in range(N)]


if __name__ == '__main__':
    print(*solve())

Submission status: Accepted

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
from typing import Iterable
import sys
def main(N, M, K, AB, CD):
    friend_chain = UnionFindTree(N)
    friend_count = [0] * N
    block_count = [0] * N
    for a, b in AB:
        a, b = a - 1, b - 1
        friend_chain.union(a, b)
        friend_count[a] += 1
        friend_count[b] += 1
    for c, d in CD:
        c, d = c - 1, d - 1
        if friend_chain.same(c, d):
            block_count[c] += 1
            block_count[d] += 1
    print(*[friend_chain.size(i) - 1 - friend_count[i] - block_count[i] for i in range(N)])

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

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

    def union(self, x: int, y: int) -> bool:
        x, y, p = self.find(x), self.find(y), self.parent
        if x == y: return False
        if p[x] > p[y]: x, y = y, x
        p[x], p[y] = p[x] + p[y], x
        return True

    def same(self, x: int, y: int) -> bool:
        return self.find(x) == self.find(y)

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

    def same_all(self, indices: Iterable[int]) -> bool:
        f, v = self.find, self.find(indices[0])
        return all(f(i) == v for i in indices)

if __name__ == '__main__':
    input = sys.stdin.readline
    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)]
    main(N, M, K, AB, CD)

Submission status: Accepted

Solution code:
from collections import deque

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

# N,M,K = [10,random.randint(1,10),random.randint(1,10)]

ad={} #友達関係
block={} #ブロック
for n in range(N):
    n=n+1
    ad[n]=set([])
    block[n]=set([])
    
for m in range(M):
    m1,m2 = list(map(int,input().split()))
    ad[m1].add(m2)
    ad[m2].add(m1)

for k in range(K):
    k1,k2 = list(map(int,input().split()))
    block[k1].add(k2)
    block[k2].add(k1)

visit = deque([])
color={}
tree={}
t=0
for n in range(N):
    n=n+1
    color[n] = -1
    tree[n] = -1
    
start_ = 1
    
while len(visit) < N:
    t += 1
    for c_k in range(start_,N):
        if color[c_k] == -1:
            start = c_k
            start_ = start + 1
            break
    color[start] = 0
    tree[start] = t
    visit_temp=deque([start])

    while len(visit_temp) > 0: #BFS
        start=visit_temp[0]
        for v in ad[start] :
            if color[v] == -1: #未訪問
                visit_temp.append(v)
                color[v] = 0
                
        color[start] = 1
        tree[start] = t
        
        pop_ = visit_temp.popleft()
        visit.append(pop_)
        
tree_={}
for v in set(tree.values()):
    tree_[v]=set()
    
for k in set(tree.keys()):
    tree_[tree[k]].add(k)
    
ans=[]
for n in range(N):
#     print('===')
    n=n+1
    
    tree_len=len(tree_[tree[n]])
    friend_len=len(ad[n])
    
    brock_len=0
    for b in block[n]:
        if tree[n] == tree[b]:
            brock_len += 1
            
#     print(tree_len,friend_len,brock_len)
#     print(tree_len-friend_len-brock_len-1)
    ans.append(tree_len-friend_len-brock_len-1)
            
print(' '.join(map(str,ans)))

Submission status: Accepted

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

class UnionFind:
    def __init__(self, numV):
        self.pars = list(range(numV))
        self.ranks = [0] * numV
        self.sizes = [1] * numV
    def getRoot(self, x):
        par = self.pars[x]
        if par != x:
            self.pars[x] = par = self.getRoot(par)
        return par
    def merge(self, x, y):
        x, y = self.getRoot(x), self.getRoot(y)
        sx, sy = self.sizes[x], self.sizes[y]
        if x == y: return (0, 0)
        if self.ranks[x] < self.ranks[y]:
            self.pars[x] = y
            self.sizes[y] += sx
        else:
            self.pars[y] = x
            self.sizes[x] += sy
            if self.ranks[x] == self.ranks[y]:
                self.ranks[x] += 1
        return (sx, sy)
    def isSame(self, x, y):
        return self.getRoot(x) == self.getRoot(y)
    def updatePars(self):
        for v in range(len(self.pars)):
            self.getRoot(v)
    def getSize(self, x):
        return self.sizes[self.getRoot(x)]

N, M, K = map(int, input().split())
UF = UnionFind(N)
anss = [-1] * N
for _ in range(M):
    A, B = map(int, input().split())
    A, B = A-1, B-1
    UF.merge(A, B)
    anss[A] -= 1
    anss[B] -= 1

for i in range(N):
    anss[i] += UF.getSize(i)

for _ in range(K):
    C, D = map(int, input().split())
    C, D = C-1, D-1
    if UF.isSame(C, D):
        anss[C] -= 1
        anss[D] -= 1

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

Submission status: Accepted

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

par=[-1]*N
num=[0]*N

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

def union(x,y):
  p,q=find(x),find(y)
  if p==q:
    return
  if p>q:
    p,q=q,p
  par[p]+=par[q]
  par[q]=p   

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

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

for _ in range(M):
  a,b=map(int,input().split())
  a-=1
  b-=1
  union(a,b)
  num[a]+=1
  num[b]+=1

for _ in range(K):
  c,d=map(int,input().split())
  c-=1
  d-=1
  if same(c,d):
    num[c]+=1
    num[d]+=1

for i in range(N):
  print(size(i)-1-num[i],end=" ")

Submission status: Accepted

Solution code:
from collections import deque


def init_tree(x, par):
    for i in range(x + 1):
        par[i] = i


def find(x, par):
    q = deque()
    q.append(x)
    while len(q) > 0:
        v = q.pop()
        if v == par[v]:
            return v
        q.append(par[v])


def union(x, y, par, rank):
    px, py = find(x, par), find(y, par)
    if px == py:
        return
    if rank[px] < rank[py]:
        par[px] = py
        return
    elif rank[px] == rank[py]:
        rank[px] += 1
    par[py] = px


n, m, k = map(int, input().split())
par = [0] * (n + 1)
rank = [0] * (n + 1)
init_tree(n, par)
eg = [[] for _ in range(n + 1)]
for _ in range(m):
    a, b = map(int, input().split())
    union(a, b, par, rank)
    eg[a].append(b)
    eg[b].append(a)
for _ in range(k):
    a, b = map(int, input().split())
    eg[a].append(b)
    eg[b].append(a)

xs = [0] * (n + 1)
ys = [0] * (n + 1)
for i in range(1, n + 1):
    p = find(i, par)
    xs[p] += 1
    for v in eg[i]:
        if p == find(v, par):
            ys[i] += 1

ans = [-1] * (n + 1)
for i in range(1, n + 1):
    ans[i] += xs[find(i, par)] - ys[i]
ans = [-1] * (n + 1)
for i in range(1, n + 1):
    ans[i] += xs[find(i, par)] - ys[i]
print(*ans[1:])

Submission status: Accepted

Solution code:
from collections import deque


def init_tree(x, par):
    for i in range(x + 1):
        par[i] = i


def find(x, par):
    q = deque()
    q.append(x)
    while len(q) > 0:
        v = q.pop()
        if v == par[v]:
            return v
        q.append(par[v])


def union(x, y, par, rank):
    px, py = find(x, par), find(y, par)
    if px == py:
        return
    if rank[px] < rank[py]:
        par[px] = py
        return
    elif rank[px] == rank[py]:
        rank[px] += 1
    par[py] = px


n, m, k = map(int, input().split())
par = [0] * (n + 1)
rank = [0] * (n + 1)
init_tree(n, par)
eg = [[] for _ in range(n + 1)]
for _ in range(m):
    a, b = map(int, input().split())
    union(a, b, par, rank)
    eg[a].append(b)
    eg[b].append(a)
for _ in range(k):
    a, b = map(int, input().split())
    eg[a].append(b)
    eg[b].append(a)

xs = [0] * (n + 1)
ys = [0] * (n + 1)
for i in range(1, n + 1):
    p = find(i, par)
    xs[p] += 1
    for v in eg[i]:
        if p == find(v, par):
            ys[i] += 1

ans = [-1] * (n + 1)
for i in range(1, n + 1):
    ans[i] += xs[find(i, par)] - ys[i]
print(*ans[1:])

Submission status: Accepted

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

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())
      
uf = UnionFind(N)      
V = [[] for _ in range(N)]

for _ in range(M):
  a,b = map(int, input().split())
  a,b = a-1, b-1
  V[a].append(b)
  V[b].append(a)
  uf.union(a,b)
  
for _ in range(K):
  a,b = map(int, input().split())
  a,b = a-1, b-1
  if uf.same(a,b):
    V[a].append(b)
    V[b].append(a)

ans = [-1] * N
for i in range(N):
  ans[i] = uf.size(i) - len(V[i]) - 1
  
print(" ".join(list(map(str, ans))))

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

import sys
sys.setrecursionlimit(10**9)
n,m,k=[int(i) for i in input().split()]
frends_num=[0 for i in range(n)]
def make_frends(m,n):
    data=[1 for i in range(m)]

    row=[]
    col=[]
    for k in range(m):
        i,j=[int(l) for l in input().split()]
        new_i=min(i,j)-1
        new_j=max(i,j)-1
        row.append(new_i)
        col.append(new_j)
        frends_num[new_i]+=1
        frends_num[new_j]+=1
    frend_sparce_matrix=csr_matrix((data, (row, col)),shape=(n,n))
    return frend_sparce_matrix


frends=make_frends(m,n)
l,labels=connected_components(frends)
labels
labels=list(labels)

class Group:
    def __init__(self,labels):
        self.labels=labels
        self.group_num=[0 for i in range(l)]
        for i in labels:
            self.group_num[i]+=1
    def get_group_num(self,i):
        return self.group_num[self.labels[i]]

group=Group(labels)


def get_frend_num(i):
    return frends_num[i]


def make_block(k,n):
    block_num=[0 for i in range(n)]
    for p in range(k):
        i,j =[int(l)-1 for l in input().split()]
        new_i=min(i,j)
        new_j=max(i,j)
        if labels[new_i]==labels[new_j]:
            block_num[i]+=1
            block_num[j]+=1
    return block_num

block=make_block(k,n)

def get_block_num(i):
    return block[i]

ans=[]
for i in range(n):
    ans.append(str(group.get_group_num(i)-1-get_frend_num(i)-get_block_num(i)))
print(" ".join(ans))

Submission status: Accepted

Solution code:
import sys
# 再帰回数上弦を100000回に設定
sys.setrecursionlimit(100000)
# スタックサイズを無制限に設定
# resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))

class UnionFind:
    """
    子ノードには自分の親ノードIDを記録。親ノードにはグループサイズの負値を記録。
    """

    def __init__(self, n):
        self.node = [-1] * n
    
    def unite(self, x, y):
        """
        xとyが属するグループを統合
        """
        # xとyの親ノードインデックスを取得
        _x, _y = self.find(x), self.find(y)
        # 一致していれば同じグループに属しているので処理終了。
        # Falseはなぞ。
        if _x == _y:
            return False
        # サイズが小さいグループを大きいグループに結合するので、
        # _y側の絶対値がかならず小さくなるように前処理。(_yを_xのグループへ統合)
        # 大きい方を小さい方へ結合してしまうとノードが深くなってしまうので、
        # 計算量を削減するためのテクニック。
        if abs(self.node[_x]) < abs(self.node[_y]):
             self.node[_x], self.node[_y] = self.node[_y], self.node[_x]
        # グループサイズ更新
        self.node[_x] += self.node[_y]
        # _yの親ノードを_xに更新
        self.node[_y] = _x
        return True

    def find(self, x):
        """
        xが属するグループの親ノードインデックスを検索。
        """
        _val = self.node[x]
        # 負なら親ノードとみなして、そのインデックスを返す。
        if _val < 0: 
            return x
        # グループの親ノードを再帰的に検索。
        # さらに、グループの親ノードIDを子ノードに記録しておくことで
        # 経路縮小を実現。
        self.node[x] = self.find(_val)
        return self.node[x]

    def same(self, x, y):
        """
        xとyが属するグループが同じかチェック。
        """
        return self.find(x) == self.find(y)

    def size(self, x):
        """
        xが属するグループの総サイズ取得
        """
        return abs(self.node[self.find(x)])
 
    def __str__(self):
        return str(self.node)

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

uf = UnionFind(N)
friend = [0] * N
block = [[] for _ in range(N)]

for _ in range(M):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    uf.unite(a, b)
    friend[a], friend[b] = friend[a] + 1, friend[b] + 1

for _ in range(K):
    c, d = map(int, input().split())
    c, d = c - 1, d - 1
    block[c].append(d)
    block[d].append(c)

for i in range(N):
    ans = uf.size(i) - friend[i] - 1
    for j in block[i]:
        if uf.same(i, j):
            ans -= 1
    print("{} ".format(ans), end="")
print("")