結果

問題 No.2598 Kadomatsu on Tree
ユーザー hirayuu_yc
提出日時 2023-12-18 19:43:02
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 853 ms / 2,000 ms
コード長 1,036 bytes
コンパイル時間 316 ms
コンパイル使用メモリ 82,392 KB
実行使用メモリ 176,272 KB
最終ジャッジ日時 2024-09-27 17:14:01
合計ジャッジ時間 32,266 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 60
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
MOD=998244353
def pairs(arr):
    add=0
    squ=0
    for i in arr:
        add+=i
        squ+=i*i
    return (add*add-squ)//2
N=int(input())
tree=[set() for i in range(N)]
for i in range(N-1):
    U,V=map(int,input().split())
    tree[U-1].add(V-1)
    tree[V-1].add(U-1)
A=list(map(int,input().split()))
top=[]
vert=deque([0])
dp=[-1]*N
while len(vert)>0:
    pos=vert.popleft()
    top.append(pos)
    dp[pos]=0
    for i in tree[pos]:
        if dp[i]==-1:
            vert.append(i)
for i in reversed(top):
    for j in tree[i]:
        dp[i]+=dp[j]
    dp[i]+=1
ans=0
for i in range(N):
    rem=-1
    less=[]
    gre=[]
    for j in tree[i]:
        if dp[i]<dp[j]:
            rem=j
            continue
        if A[i]<A[j]:
            less.append(dp[j])
        elif A[i]>A[j]:
            gre.append(dp[j])
    if rem!=-1:
        if A[i]<A[rem]:
            less.append(N-dp[i])
        elif A[i]>A[rem]:
            gre.append(N-dp[i])
    ans+=pairs(less)+pairs(gre)
    ans%=MOD
print(ans)
0