- ์๊ณ ๋ฆฌ์ฆ ์คํฐ๋ ๋ฌธ์ ํ์ด์ ๋๋ค.
- ๋ฐฑ์ค 1068๋ฒ ์์ ํ์ด๋ณผ ์ ์์ต๋๋ค.
- ํธ๋ฆฌ์์ ๋ฆฌํ ๋ ธ๋๋, ์์์ ๊ฐ์๊ฐ 0์ธ ๋ ธ๋๋ฅผ ๋งํ๋ค. ํธ๋ฆฌ๊ฐ ์ฃผ์ด์ก์ ๋, ๋ ธ๋ ํ๋๋ฅผ ์ง์ธ ๊ฒ์ด๋ค. ๊ทธ ๋, ๋จ์ ํธ๋ฆฌ์์ ๋ฆฌํ ๋ ธ๋์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค. ๋ ธ๋๋ฅผ ์ง์ฐ๋ฉด ๊ทธ ๋ ธ๋์ ๋ ธ๋์ ๋ชจ๋ ์์์ด ํธ๋ฆฌ์์ ์ ๊ฑฐ๋๋ค.
- ์ฒซ์งธ ์ค์ ํธ๋ฆฌ์ ๋ ธ๋์ ๊ฐ์ N์ด ์ฃผ์ด์ง๋ค. N์ 50๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ์์ฐ์์ด๋ค. ๋์งธ ์ค์๋ 0๋ฒ ๋ ธ๋๋ถํฐ N-1๋ฒ ๋ ธ๋๊น์ง, ๊ฐ ๋ ธ๋์ ๋ถ๋ชจ๊ฐ ์ฃผ์ด์ง๋ค. ๋ง์ฝ ๋ถ๋ชจ๊ฐ ์๋ค๋ฉด (๋ฃจํธ) -1์ด ์ฃผ์ด์ง๋ค. ์ ์งธ ์ค์๋ ์ง์ธ ๋ ธ๋์ ๋ฒํธ๊ฐ ์ฃผ์ด์ง๋ค.
from collections import deque
n = int(input())
arr_node = list(map(int, input().split(" ")))
delete = int(input())
class Node:
def __init__(self, value, parent):
self.value = value
self.parent = parent
self.child = []
def find(self, root, value):
node = None
def recur(curr):
nonlocal node
if curr.value == value:
node = curr
return
for i in curr.child:
recur(i)
recur(root)
return node
def solution():
val_nodes = []
for value, node in enumerate(arr_node):
val_nodes.append(Node(value, node))
for i in val_nodes:
for j in val_nodes:
if i.value == j.parent:
i.child.append(j)
val_nodes = sorted(val_nodes, key=lambda x : x.parent)
for i in val_nodes:
if i.value == delete:
if i.parent == -1:
print(0)
return
children = i.find(val_nodes[0], i.parent).child
if not children:
break
else:
children.remove(i)
count = 0
dq = deque([])
dq.append(val_nodes[0])
while dq:
node = dq.popleft()
if not node.child:
count += 1
else:
for i in node.child:
dq.append(i)
print(count)
solution()
dfs ๋ก ์ํํ๋ฉด์ ๋ฆฌํ๋
ธ๋ ๊ฐ์๋ฅผ ์ถ๊ฐํ๋ค.
๋ง์ฝ ๋
ธ๋๊ฐ ์ ๊ฑฐํด์ผํ๋ ๋
ธ๋์ผ ๊ฒฝ์ฐ, ๋ถ๋ชจ์ ์์ ๊ฐ์๋ฅผ ํ์ธํ๋ค.
์์์ด ํ ๊ฐ์ผ ๊ฒฝ์ฐ ํด๋น๋
ธ๋๋ฅผ ์ ๊ฑฐํ๋ฉด ๋ถ๋ชจ๊ฐ ๋ฆฌํ๋
ธ๋๊ฐ ๋๋ฏ๋ก ๋ฆฌํ๋
ธ๋ ๊ฐ์๋ฅผ ์ถ๊ฐํ๋ค.
from sys import stdin
def dfs(idx):
if idx not in children:
ans[0] += 1
return
for c in children[idx]:
if c == delnode:
if len(children[idx]) < 2:
ans[0] += 1
continue
dfs(c)
n = int(stdin.readline())
info = list(map(int, stdin.readline().split()))
delnode = int(stdin.readline())
children = dict()
root = 0
ans = [0]
for i, par in enumerate(info):
if par == -1:
root = i
continue
if par in children:
children[par].append(i)
else:
children[par] = [i]
if delnode == root:
print(0)
else:
dfs(root)
print(ans[0])
N = int(input())
arr = list(map(int, input().split()))
removed = int(input()) # ์ญ์ ๋ ๋
ธ๋
leafs = []
root = -1
for index in range(N):
if arr[index] == -1: # ๋ฃจํธ ๋
ธ๋ ์ฐพ๊ธฐ
root = index
if index not in arr: # leaf๋
ธ๋ ์ฐพ๊ธฐ
leafs.append(index)
parent = arr[removed]
for index in range(N):
cur = index
while cur != -1:
if cur == removed:
if index in leafs:
leafs.remove(index) # ๋ฆฌํ๋
ธ๋์์ ์ญ์
break
cur = arr[cur]
count = 0 # ์ญ์ ํ ๋
ธ๋์ ๋ถ๋ชจ๊ฐ ๊ฐ์ง ์์์ ์
for elem in arr:
if elem == parent:
count += 1
if removed == root : # ์ญ์ ํ ๋
ธ๋๊ฐ ๋ถ๋ชจ์ผ๊ฒฝ์ฐ 0
print(0)
elif count == 1: # ์์์ ์๊ฐ 1์ธ ๊ฒฝ์ฐ leaf ํ๊ฐ ์ถ๊ฐ
print(len(leafs)+1)
else:
print(len(leafs))