結果

問題 No.2205 Lights Out on Christmas Tree
コンテスト
ユーザー Theta
提出日時 2023-02-06 15:16:14
言語 Python3
(3.14.3 + numpy 2.4.4 + scipy 1.17.1)
コンパイル:
python3 -mpy_compile _filename_
実行:
python3 _filename_
結果
AC  
実行時間 640 ms / 2,000 ms
コード長 1,246 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 487 ms
コンパイル使用メモリ 20,572 KB
実行使用メモリ 79,476 KB
最終ジャッジ日時 2026-03-26 02:34:08
合計ジャッジ時間 19,315 ms
ジャッジサーバーID
(参考情報)
judge3_1 / judge1_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

def main():
    N = int(input())

    graphs = [[] for _ in range(N)]
    for _ in range(N-1):
        dep, dest = map(lambda n: int(n)-1, input().split())
        graphs[dep].append(dest)
        graphs[dest].append(dep)
    color = list(map(int, input().split()))
    if color.count(0) % 2:
        print(-1)
        return

    moved = set()
    searched = set()
    stack = []
    stack.append([0, None])
    moved.add(0)
    change_ctr = 0
    while stack:
        ctr_child = 0
        current_notice_node, notice_node_parent = stack[-1]
        for node_idx in graphs[current_notice_node]:
            if node_idx not in moved:
                stack.append((node_idx, current_notice_node))
                moved.add(node_idx)
                ctr_child += 1
        if ctr_child == 0:
            current_node_idx, parent_idx = stack.pop()
            if color[current_node_idx] == 0:
                if parent_idx is not None:
                    color[current_node_idx] = 1
                    color[parent_idx] ^= 1
                    change_ctr += 1
                else:
                    print(-1)
                    return
            searched.add(current_node_idx)

    print(change_ctr)


if __name__ == "__main__":
    main()
0