結果

問題 No.386 貪欲な領主
ユーザー titiatitia
提出日時 2023-01-30 03:07:28
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 1,972 ms / 2,000 ms
コード長 1,947 bytes
コンパイル時間 618 ms
コンパイル使用メモリ 10,992 KB
実行使用メモリ 106,860 KB
最終ジャッジ日時 2023-09-12 07:59:11
合計ジャッジ時間 11,353 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 32 ms
8,760 KB
testcase_01 AC 25 ms
8,760 KB
testcase_02 AC 25 ms
8,840 KB
testcase_03 AC 27 ms
8,940 KB
testcase_04 AC 1,429 ms
106,336 KB
testcase_05 AC 1,908 ms
49,052 KB
testcase_06 AC 1,972 ms
53,732 KB
testcase_07 AC 33 ms
8,956 KB
testcase_08 AC 220 ms
12,816 KB
testcase_09 AC 42 ms
9,144 KB
testcase_10 AC 23 ms
8,920 KB
testcase_11 AC 25 ms
8,768 KB
testcase_12 AC 31 ms
8,792 KB
testcase_13 AC 57 ms
10,188 KB
testcase_14 AC 1,940 ms
53,948 KB
testcase_15 AC 1,102 ms
106,860 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

sys.setrecursionlimit(10**7)

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

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

U=[int(input()) for i in range(N)]

ROOT=0

QUE=[ROOT] 
Parent=[-1]*(N+1)
Parent[ROOT]=N # ROOTの親を定めておく.
Child=[[] for i in range(N+1)]
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)

Children=[1]*(N+1)

for x in TOP_SORT[::-1]: #(自分を含む)子ノードの数を調べる
    Children[Parent[x]]+=Children[x]
    
USE=[0]*N
Group=[i for i in range(N)]

for x in TOP_SORT: # HL分解によるグループ分け
    USE[x]=1
    MAX_children=0
    select_node=0

    for to in E[x]:
        if USE[to]==0 and Children[to]>MAX_children:
            select_node=to
            MAX_children=Children[to]

    for to in E[x]:
        if USE[to]==0 and to==select_node:
            Group[to]=Group[x]

def LCA(a,b): # HL分解を利用してLCAを求める
    while Group[a]!=Group[b]:
        if Children[Parent[Group[a]]]<Children[Parent[Group[b]]]:
            a=Parent[Group[a]]
        else:
            b=Parent[Group[b]]

    if Children[a]>Children[b]:
        return a
    else:
        return b
    
from functools import lru_cache
@lru_cache(maxsize=None)
def calc(x):
    if x==N:
        return 0
    if x==ROOT:
        return U[x]
    else:
        return U[x]+calc(Parent[x])


ANS=0

m=int(input())

for i in range(m):
    a,b,c=map(int,input().split())

    x=LCA(a,b)

    if x==a:
        ANS+=c*(calc(b)-calc(Parent[a]))
    elif x==b:
        ANS+=c*(calc(a)-calc(Parent[b]))
    else:
        ANS+=c*(calc(a)+calc(b)-calc(x)-calc(Parent[x]))

print(ANS)
        
0