lainroses   6년 전

시간초과 어떻게 해야할까요...?
bfs로 탐색하면서 자식 노드 list 가져올 때 parent list에 부모노드를 저장하는 구조입니다.

```python

def search(tree, root=1):
    queue = [root]
    visited = []
    parent = [0]*(len(tree)+1)
    while queue:
        visit = queue.pop(0)
        visited += [visit]
        child = list(set(tree[visit]) - set(visited))
        for c in child: parent[c] = visit
        queue += child
    return parent
tree = {}
for _ in '-'*(input()-1):
    a,b = map(int, raw_input().split())
    if not a in tree: tree[a] = []
    if not b in tree: tree[b] = []
    tree[a] += [b]
    tree[b] += [a]
for i in search(tree)[2:]: print i

jh05013   6년 전

문제 번호를 넣어 주세요.

그리고 pop(0)는 첫 원소를 빼면서 나머지를 한 칸씩 일일히 왼쪽으로 옮깁니다. 절대로, 절대로 하면 안 됩니다.

댓글을 작성하려면 로그인해야 합니다.