結果

問題 No.1484 木に数を書き込む問題 / Just Write Numbers! 2
ユーザー t98slidert98slider
提出日時 2023-02-07 00:01:49
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 169 ms / 2,000 ms
コード長 1,265 bytes
コンパイル時間 1,799 ms
コンパイル使用メモリ 175,264 KB
実行使用メモリ 36,712 KB
最終ジャッジ日時 2023-09-18 09:31:56
合計ジャッジ時間 7,750 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 3 ms
4,376 KB
testcase_05 AC 8 ms
4,380 KB
testcase_06 AC 9 ms
4,384 KB
testcase_07 AC 5 ms
4,376 KB
testcase_08 AC 10 ms
4,536 KB
testcase_09 AC 9 ms
4,416 KB
testcase_10 AC 9 ms
4,532 KB
testcase_11 AC 7 ms
4,376 KB
testcase_12 AC 6 ms
4,376 KB
testcase_13 AC 2 ms
4,376 KB
testcase_14 AC 116 ms
15,144 KB
testcase_15 AC 112 ms
14,240 KB
testcase_16 AC 100 ms
13,500 KB
testcase_17 AC 65 ms
10,808 KB
testcase_18 AC 138 ms
16,204 KB
testcase_19 AC 169 ms
18,192 KB
testcase_20 AC 166 ms
18,128 KB
testcase_21 AC 167 ms
18,408 KB
testcase_22 AC 166 ms
18,116 KB
testcase_23 AC 164 ms
18,040 KB
testcase_24 AC 163 ms
18,028 KB
testcase_25 AC 167 ms
18,136 KB
testcase_26 AC 166 ms
18,188 KB
testcase_27 AC 164 ms
18,180 KB
testcase_28 AC 168 ms
18,108 KB
testcase_29 AC 80 ms
36,712 KB
testcase_30 AC 87 ms
25,340 KB
testcase_31 AC 55 ms
19,596 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    vector<vector<int>> g(n);
    for(int i = 1; i < n; i++){
        int u, v;
        cin >> u >> v;
        g[--u].push_back(--v);
        g[v].push_back(u);
    }
    auto bfs = [&](int from){
        queue<int> nxt;
        vector<int> dist(n, 1 << 30);
        dist[from] = 0;
        nxt.push(from);
        while(!nxt.empty()){
            int v = nxt.front();
            nxt.pop();
            for(auto &u : g[v]){
                if(dist[v] + 1 >= dist[u]) continue;
                dist[u] = dist[v] + 1;
                nxt.push(u);
            }
        }
        return dist;
    };
    auto dist = bfs(0);
    int root = max_element(dist.begin(), dist.end()) - dist.begin();
    vector<ll> dp(n), dp2(n);
    function<void(int, int)> dfs = [&](int v, int p){
        ll s = 0, mx = 0;
        for(auto &u : g[v]){
            if(u == p) continue;
            dfs(u, v);
            dp[u] += 2;
            dp2[u]++;
            mx = max(mx, dp[u] - dp2[u]);
            s += dp[u];
        }
        dp[v] = s;
        dp2[v] = s - mx;
    };
    dfs(root, -1);
    cout << dp2[root] << '\n';
}
0