Official

C - 二分決定木の検証 / Verification of Binary Decision Trees Editorial by sounansya


条件を満たしているか適切にチェックすれば良いです。

再帰関数で実装すると楽に実装できると思います。

実装例(Python3)

import sys

input = sys.stdin.readline
sys.setrecursionlimit(10**7)


def no():
    print("NO")
    exit()


n, m = map(int, input().split())
if m != n - 1:
    no()
l = [0] * n
r = [0] * n
p = [0] * n
q = [0] * n
for i in range(n):
    l[i], r[i], p[i], q[i] = map(int, input().split())
g = [[[] for _ in range(n)] for _ in range(2)]
for _ in range(m):
    u, v, b = map(int, input().split())
    g[b][u - 1].append(v - 1)
used = [False] * n


def f(u):
    if used[u]:
        no()
    used[u] = True
    if len(g[0][u]) > 1 or len(g[1][u]) > 1:
        no()
    for i in range(2):
        if len(g[i][u]) == 1:
            v = g[i][u][0]
            if not (l[u] < l[v] and r[v] < r[u]):
                no()
            if p[v] != q[u]:
                no()
            f(v)
    if len(g[0][u]) == 1 and len(g[1][u]) == 1:
        x, y = g[0][u][0], g[1][u][0]
        if r[x] >= l[y]:
            no()


f(0)
for i in range(n):
    if not used[i]:
        no()
print("YES")

posted:
last update: