結果
問題 | No.439 チワワのなる木 |
ユーザー |
![]() |
提出日時 | 2025-01-13 02:35:23 |
言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
結果 |
AC
|
実行時間 | 765 ms / 5,000 ms |
コード長 | 1,153 bytes |
コンパイル時間 | 1,205 ms |
コンパイル使用メモリ | 12,160 KB |
実行使用メモリ | 47,360 KB |
最終ジャッジ日時 | 2025-01-13 02:35:34 |
合計ジャッジ時間 | 9,114 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 28 |
ソースコード
import sys input = sys.stdin.readline N=int(input()) S=input().strip() 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) # 木のHL分解+LCA 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) C=[0]*N W=[0]*N for x in TOP_SORT[::-1]: #(自分を含む)子ノードの数を調べる if S[x]=="c": C[x]+=1 else: W[x]+=1 if x==0: break C[Parent[x]]+=C[x] W[Parent[x]]+=W[x] ANS=0 SUMC=C[0] SUMW=W[0] for i in range(N): if S[i]=="w": SC=0 SW=0 for c in Child[i]: cc=C[c] cw=W[c] ANS+=cc*(SUMW-cw-1) SC+=cc SW+=cw ANS+=(SUMC-SC)*SW print(ANS)