結果
| 問題 | No.1817 Reversed Edges | 
| コンテスト | |
| ユーザー |  titia | 
| 提出日時 | 2022-01-21 21:56:10 | 
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) | 
| 結果 | 
                                WA
                                 
                             | 
| 実行時間 | - | 
| コード長 | 2,639 bytes | 
| コンパイル時間 | 342 ms | 
| コンパイル使用メモリ | 12,928 KB | 
| 実行使用メモリ | 48,412 KB | 
| 最終ジャッジ日時 | 2024-11-25 23:54:21 | 
| 合計ジャッジ時間 | 18,775 ms | 
| ジャッジサーバーID (参考情報) | judge4 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 2 | 
| other | AC * 4 WA * 19 | 
ソースコード
import sys
input = sys.stdin.readline
N=int(input())
E=[[] for i in range(N)]
for i in range(N-1):
    x,y=map(int,input().split())
    x-=1
    y-=1
    E[x].append(y)
    E[y].append(x)
    
ROOT=0
QUE=[ROOT] 
Parent=[-1]*N
Parent[ROOT]=N # ROOTの親を定めておく.
TOP_SORT=[] # トポロジカルソート
Child=[[] for i in range(N)]
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)
UP=[0]*N
DOWN=[0]*N
# xとParent[x]をつなぐedgeを考える
# UP[x]は、xをROOTとする部分木に関する値。
# xとつながるnodeのうち、Parent[x]以外をxの子と捉える。
# DOWN[x]はParent[x]をROOTとする部分木に関する値。
# Parent[x]とつながるnodeのうち、x以外をParent[x]の子と捉える。
def compose_calc(x,y):# 子たちの値を合成する
    return x+y
unit=0 # 単位元
def final_ans(x,value):# 子たちから計算した値から答えを出す
    return value
for x in TOP_SORT[1:][::-1]:
    if Child[x]==[]:
        UP[x]=0
        continue
    
    k=unit # 子が全て1なら0、それ以外は1
    for c in Child[x]:
        k=compose_calc(k,UP[c])
        if c<x:
            k+=1
    UP[x]=k
COMPOSE=[1]*N
# DOWN[x]を求めるときに使う
# Parent[x]について、Parent[Parent[x]]以外からの寄与。
# 各iについて、for c in Child[i]についてUP[c]の値をみて、左右からの累積和を使って計算。
for i in range(N):
    X=[]
    for c in Child[i]:
        X.append(UP[c])
    if X==[]:
        continue
    LEFT=[X[0]]
    for j in range(1,len(X)):
        LEFT.append(compose_calc(LEFT[-1],X[j]))
    RIGHT=1
    for j in range(len(X)-1,-1,-1):
        if j!=0:
            COMPOSE[Child[i][j]]=compose_calc(LEFT[j-1],RIGHT)
        else:
            COMPOSE[Child[i][j]]=RIGHT
        RIGHT=compose_calc(RIGHT,X[j])
for x in TOP_SORT:
    if x==ROOT:
        DOWN[x]=0
        continue
    p=Parent[x]
    
    if p==ROOT:
        k=COMPOSE[x]
    else:
        k=compose_calc(DOWN[p],COMPOSE[x])
    DOWN[x]=final_ans(x,k)
ANS=[0]*N
# iをROOTとしたときの値は、
# for c in Child[i]についてのUP[c]とDOWN[i]から求められる。
for i in range(N):
    k=unit
    for c in Child[i]:
        k=compose_calc(k,UP[c])
        if c<i:
            k+=1
    if i!=ROOT:
        k=compose_calc(k,DOWN[i])
        if Parent[i]>i:
            k+=1
    ANS[i]=final_ans(i,k)
for ans in ANS:
    print(ans)
            
            
            
        