結果

問題 No.2949 Product on Tree
ユーザー shimon
提出日時 2024-11-04 10:38:37
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 665 ms / 2,000 ms
コード長 1,406 bytes
コンパイル時間 521 ms
コンパイル使用メモリ 82,392 KB
実行使用メモリ 140,224 KB
最終ジャッジ日時 2024-11-04 10:39:08
合計ジャッジ時間 29,108 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

# 全方位木DP
from collections import deque
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
mod = 998244353
X = [[] for i in range(N)]
for i in range(N - 1):
    x, y = map(int, input().split())
    X[x - 1].append(y - 1)
    X[y - 1].append(x - 1)

P = [-1] * N
Q = deque([0])
R = []
while Q:
    i = deque.popleft(Q)
    R.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)

# Settings
unit = 0
def merge(a, b): return (a + b) % mod
def adj_bu(a, i): return (a + 1) * A[i] % mod
def adj_td(a, i, p): return (a + 1) * A[p] % mod
def adj_fin(a, i): return (a + 1) * A[i] % mod
#####


ME = [unit] * N
XX = [0] * N
TD = [unit] * N
for i in R[1:][::-1]:
    XX[i] = adj_bu(ME[i], i)
    p = P[i]
    ME[p] = merge(ME[p], XX[i])
XX[R[0]] = adj_fin(ME[R[0]], R[0])

# print("ME =", ME) # Merge before adj
# print("XX =", XX) # Bottom-up after adj

for i in R:
    ac = TD[i]
    for j in X[i]:
        TD[j] = ac
        ac = merge(ac, XX[j])
    ac = unit
    for j in X[i][::-1]:
        TD[j] = adj_td(merge(TD[j], ac), j, i)
        ac = merge(ac, XX[j])
        XX[j] = adj_fin(merge(ME[j], TD[j]), j)

# print("TD =", TD) # Top-down after adj
# print("XX =", XX) # Final Result

s = 0
for x in XX:
    s += x
    s %= mod

s -= sum(A)
s *= pow(2, mod - 2, mod)
s %= mod
print(s)
0