結果

問題 No.3514 Majority Driven Tree
コンテスト
ユーザー titia
提出日時 2026-04-28 07:01:01
言語 PyPy3
(7.3.17)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 85 ms / 2,000 ms
コード長 1,490 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 362 ms
コンパイル使用メモリ 85,120 KB
実行使用メモリ 84,224 KB
最終ジャッジ日時 2026-04-28 07:01:08
合計ジャッジ時間 4,927 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge2_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys
input = sys.stdin.readline

N=int(input())

E=[[] for i in range(N)]

for i in range(N-1):
    a,b=list(map(int,input().split()))
    a-=1
    b-=1
    E[a].append(b)
    E[b].append(a)

ROOT=0

QUE=[ROOT] 
Parent=[-1]*N
Parent[ROOT]=N # ROOTの親を定めておく.
Child=[[] for i in range(N)]
TOP_SORT=[] # トポロジカルソート

while QUE: # トポロジカルソートと同時に親を見つける
    x=QUE.pop()
    TOP_SORT.append(x)
    for to in E[x]:
        if Parent[to]==-1:
            Parent[to]=x
            Child[x].append(to)
            QUE.append(to)


DP1=[1<<31]*N # 部分木全部を黒くするコスト
DP2=[1<<31]*N # 親が黒のとき、部分木全部を黒くするコスト

for x in TOP_SORT[::-1]:
    if Child[x]==[]:
        DP1[x]=1
        DP2[x]=0
        continue

    score=0

    for c in Child[x]:
        score+=DP2[c]

    L=[]
    for c in Child[x]:
        L.append(DP1[c]-DP2[c])

    L.sort()
    k=len(E[x])//2+1

    #print(x,k,L)

    if len(L)>=k:

        score2=0
        for i in range(len(L)):
            if i<k:
                score2+=L[i]
            else:
                continue
    else:
        score2=1<<30

    DP1[x]=min(score+1,score2+score)

    k-=1
    score3=0

    if len(L)>=k:

        for i in range(len(L)):
            if i<k:
                score3+=L[i]
            else:
                continue
    else:
        score3+=1<<30

    DP2[x]=min(score3+score,DP1[x])

print(DP1[0])
    

0