結果

問題 No.2638 Initial fare
ユーザー mkawa2
提出日時 2025-07-01 16:25:23
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 726 ms / 2,000 ms
コード長 1,894 bytes
コンパイル時間 527 ms
コンパイル使用メモリ 82,184 KB
実行使用メモリ 176,896 KB
最終ジャッジ日時 2025-07-01 16:25:40
合計ジャッジ時間 14,247 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 25
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

# sys.setrecursionlimit(200005)
# sys.set_int_max_str_digits(200005)
int1 = lambda x: int(x)-1
pDB = lambda *x: print(*x, end="\n", file=sys.stderr)
p2D = lambda x: print(*x, sep="\n", end="\n\n", file=sys.stderr)
def II(): return int(sys.stdin.readline())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def SI(): return sys.stdin.readline().rstrip()

dij = [(0, 1), (-1, 0), (0, -1), (1, 0)]
# dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
# inf = -1-(-1 << 31)
inf = -1-(-1 << 62)

# md = 10**9+7
md = 998244353

def rerooting(root=0):
    uu = []
    stack = [root]
    while stack:
        u = stack.pop()
        uu.append(u)
        vv = []
        # !!!check the format of the "to"!!!
        for v in to[u]:
            if v == par[u]: continue
            vv.append(v)
            par[v] = u
            stack.append(v)
        to[u] = vv

    # bottom up
    for u in uu[::-1]:
        p = par[u]
        if p == -1: continue
        dp[p] = merge(dp[p], trans_up(dp[u], u))

    # top down
    for u in uu:
        p = par[u]
        if p == -1: continue
        dp[u] = merge(dp[u], trans_down(purge(dp[p], trans_up(dp[u], u)), u))

# v is child
# a is parent's value
# b is child's value
def trans_up(b, v):
    return [1]+b[:2]

def trans_down(a, v):
    return [1]+a[:2]

def merge(a, b):
    p,q,r=a
    x,y,z=b
    return [p+x,q+y,r+z]

def purge(a, b):
    p,q,r=a
    x,y,z=b
    return [p-x,q-y,r-z]

n=II()
to=[[] for _ in range(n)]
for _ in range(n-1):
    u,v=LI1()
    to[u].append(v)
    to[v].append(u)

par = [-1]*n
dp = [[0,0,0] for _ in range(n)]
rerooting()
ans=0
for u in range(n):ans+=sum(dp[u])
print(ans//2)
0