結果

問題 No.386 貪欲な領主
ユーザー mkawa2
提出日時 2020-03-27 17:34:55
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,899 bytes
コンパイル時間 111 ms
コンパイル使用メモリ 12,416 KB
実行使用メモリ 102,144 KB
最終ジャッジ日時 2025-01-02 08:58:44
合計ジャッジ時間 10,532 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 15 TLE * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

sys.setrecursionlimit(10 ** 6)

def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def SI(): return sys.stdin.readline()[:-1]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
int1 = lambda x: int(x) - 1
def MI1(): return map(int1, sys.stdin.readline().split())
def LI1(): return list(map(int1, sys.stdin.readline().split()))
p2D = lambda x: print(*x, sep="\n")
dij = [(1, 0), (0, 1), (-1, 0), (0, -1)]

def main():
    def dfs():
        stack=[(0,-1,0)]
        while stack:
            u,pu,d=stack.pop()
            dep[u]=d
            for v in to[u]:
                if pu==v:continue
                anc[0][v]=u
                stack.append((v,u,d+1))

    n=II()
    to=[[] for _ in range(n)]
    for _ in range(n-1):
        a,b=MI()
        to[a].append(b)
        to[b].append(a)
    # LCAする
    mxlv=(n-1).bit_length()
    cost=[[0]*n for _ in range(mxlv)]
    for u in range(n):cost[0][u]=II()
    anc=[[-1]*n for _ in range(mxlv)]
    dep=[0]*n
    dfs()
    for lv in range(mxlv-1):
        for u in range(n):
            v=anc[lv][u]
            anc[lv+1][u]=anc[lv][v]
            cost[lv+1][u]=cost[lv][u]+cost[lv][v]

    m=II()
    ans=0
    for _ in range(m):
        u,v,k=MI()
        if dep[u]<dep[v]:u,v=v,u
        diff=dep[u]-dep[v]
        lv=0
        while diff:
            if diff&1:
                ans+=cost[lv][u]*k
                u=anc[lv][u]
            diff>>=1
            lv+=1
        if u==v:
            ans+=cost[0][v]*k
            continue
        for lv in range(mxlv-1,-1,-1):
            alv=anc[lv]
            if alv[u]==alv[v]:continue
            ans+=(cost[lv][u]+cost[lv][v])*k
            u,v=alv[u],alv[v]
        pu=anc[0][u]
        ans+=(cost[0][u]+cost[0][v]+cost[0][pu])*k
    print(ans)

main()
0