Hits

안녕하세요. 모카의 머신러닝 입니다. 이번 포스팅에서는 백준 알고리즘 문제 풀이에 대해 포스팅하도록 하겠습니다.


코드는 이곳을 참고했음을 밝힙니다.


1. 트리

백준 11725번

https://www.acmicpc.net/problem/11725

import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

N = int(input())
visited = [False] * (N+1)
tree = [[] for _ in range(N+1)]
answer = [0] * (N+1)

for _ in range(1, N):
    n1, n2 = map(int, input().split())
    tree[n1].append(n2)
    tree[n2].append(n1)

def DFS(number):
    visited[number] = True
    for i in tree[number]:
        if not visited[i]:
            answer[i] = number
            DFS(i)

DFS(1)

for i in range(2, N+1):
    print(answer[i])


백준 1068번

https://www.acmicpc.net/problem/1068

import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
N = int(input())
visited = [False] * (N)
tree = [[] for _ in range(N)]
answer = 0
p = list(map(int, input().split()))

for i in range(N):
    if p[i] != -1:
        tree[i].append(p[i])
        tree[p[i]].append(i)
    else:
        root = i
        
def DFS(number):
    global answer
    visited[number] = True
    cNode = 0
    for i in tree[number]:
        if not visited[i] and i != deleteNode:
            cNode += 1
            DFS(i)
    if cNode == 0:
        answer += 1

deleteNode = int(input())

if deleteNode == root:
    print(0)
else:
    DFS(root)
    print(answer)


백준 14425번

https://www.acmicpc.net/problem/14425

from sys import stdin
input = stdin.readline

class Node(object):
    def __init__(self, isEnd):
        self.isEnd = isEnd
        self.childNode = {}


class Trie(object):
    def __init__(self):
        self.parent = Node(None)

    def insert(self, string):
        nowNode = self.parent
        temp_lenght = 0
        for char in string:
            if char not in nowNode.childNode:
                nowNode.childNode[char] = Node(char)
            nowNode = nowNode.childNode[char]
            temp_lenght += 1
            if temp_lenght == len(string):
                nowNode.isEnd = True

    def search(self, string):
        nowNode = self.parent
        temp_lenght = 0
        for char in string:
            if char in nowNode.childNode:
                nowNode = nowNode.childNode[char]
                temp_lenght += 1
                if temp_lenght == len(string) and nowNode.isEnd == True:
                    return True
            else:
                return False
        return False


N, M = map(int, input().split())
myTrie = Trie()

for _ in range(N):
    word = input().strip()
    myTrie.insert(word) 

result = 0
for _ in range(M):
    word = input().strip()
    if myTrie.search(word):
        result += 1
print(result)


지금까지 백준 알고리즘 트리 부분이었습니다.

읽어주셔서 감사합니다. 😃