AOJ ALDS1_7_A Rooted Trees

備忘録

問題

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_A&lang=jp

回答

import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def get_depth(parent, node):
    depth = 0
    n = node
    while True:
        if parent[n] == -1: break
        n = parent[n]
        depth += 1

    return depth


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    parent = [-1] * N
    children = collections.defaultdict(list)

    for n in range(N):
        id, k, *C = il()
        for c in C:
            children[id].append(c)
            parent[c] = id

    for node in range(N):
        depth = get_depth(parent, node)
        type = ''
        if parent[node] == -1:
            type = 'root'
        elif len(children[node]) > 0:
            type = 'internal node'
        else:
            type = 'leaf'

        print('node {0}: parent = {1}, depth = {2}, {3}, {4}'.format(node, parent[node], depth, type, children[node]))


if __name__ == '__main__':
    main()

考え方

螺旋本より木構造入門問題。
かなり愚直な実装で各Nodeのidをindexにした配列と辞書型を使用。
配列(parent = [-1] * N)には自身の親にあたるNodeを保持し、
辞書型(children = collections.defaultdict(list))には各Nodeにつながっている
子を配列として保持した。
あとは入力時に受け取った情報から愚直に求められている情報を出力して回答。