結果

問題 No.1976 Cut then Connect
ユーザー rin204rin204
提出日時 2022-06-11 15:13:20
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,974 bytes
コンパイル時間 831 ms
コンパイル使用メモリ 81,580 KB
実行使用メモリ 90,084 KB
最終ジャッジ日時 2023-10-22 00:34:42
合計ジャッジ時間 9,580 ms
ジャッジサーバーID
(参考情報)
judge9 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 40 ms
53,512 KB
testcase_01 AC 39 ms
53,512 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 WA -
testcase_21 WA -
testcase_22 WA -
testcase_23 WA -
testcase_24 AC 41 ms
53,512 KB
testcase_25 AC 40 ms
53,512 KB
testcase_26 AC 39 ms
53,512 KB
testcase_27 WA -
testcase_28 WA -
testcase_29 WA -
testcase_30 AC 39 ms
53,512 KB
testcase_31 WA -
testcase_32 AC 39 ms
53,512 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(10 ** 9)
# import pypyjit
# pypyjit.set_param('max_unroll_recursion=-1')

n = int(input())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    edges[u].append(v)
    edges[v].append(u)

max_R = [0] * n
max_dist = [0] * n

def dfs(pos, bpos):
    ma1 = 0
    ma2 = 0
    for npos in edges[pos]:
        if npos == bpos:
            continue
        dfs(npos, pos)
        if max_R[pos] < max_R[npos]:
            max_R[pos] = max_R[npos]
        if ma2 < max_dist[npos] + 1:
            ma2 = max_dist[npos] + 1
            if ma2 > ma1:
                ma1, ma2 = ma2, ma1
    max_dist[pos] = ma1
    max_R[pos] = max(max_R[pos], ma1 + ma2)

dfs(0, -1)

ans = n
def dfs2(pos, bpos):
    if bpos != -1:
        global ans
        r1 = max_R[bpos]
        r2 = max_R[pos]
        ans = min(ans, (r1 + 1) // 2 + (r2 + 1) // 2 + 1)
    ma1 = 0
    ma2 = 0
    ma3 = 0
    le = len(edges[pos])
    L_r = [0] * (le + 1)
    R_r = [0] * (le + 1)
    for i, npos in enumerate(edges[pos], 1):
        L_r[i] = max(L_r[i - 1], max_R[npos])
        if ma3 < max_dist[npos] + 1:
            ma3 = max_dist[npos] + 1
            if ma3 > ma2:
                ma2, ma3 = ma3, ma2
                if ma2 > ma1:
                    ma1, ma2 = ma2, ma1
    for i in range(le - 1, -1, -1):
        npos = edges[pos][i]
        R_r[i] = max(R_r[i + 1], max_R[npos])
    
    for i, npos in enumerate(edges[pos]):
        if npos == bpos:
            continue
        max_R[pos] = max(L_r[i], R_r[i + 1])
        if max_dist[npos] + 1 == ma1:
            max_dist[pos] = ma2
            max_R[pos] = max(max_R[pos], ma2 + ma3)
        elif max_dist[npos] + 1 == ma2:
            max_dist[pos] = ma1
            max_R[pos] = max(max_R[pos], ma1 + ma3)
        else:
            max_dist[pos] = ma1
            max_R[pos] = max(max_R[pos], ma1 + ma2)
        dfs2(npos, pos)

dfs2(0 ,-1)
print(ans)
0