結果

問題 No.277 根掘り葉掘り
ユーザー xuzijian629xuzijian629
提出日時 2018-10-30 16:28:44
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 238 ms / 3,000 ms
コード長 1,217 bytes
コンパイル時間 2,249 ms
コンパイル使用メモリ 210,560 KB
実行使用メモリ 12,160 KB
最終ジャッジ日時 2024-04-30 00:43:29
合計ジャッジ時間 6,592 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 2 ms
5,376 KB
testcase_07 AC 2 ms
5,376 KB
testcase_08 AC 2 ms
5,376 KB
testcase_09 AC 235 ms
10,240 KB
testcase_10 AC 203 ms
11,412 KB
testcase_11 AC 233 ms
12,160 KB
testcase_12 AC 224 ms
11,264 KB
testcase_13 AC 238 ms
11,136 KB
testcase_14 AC 222 ms
11,264 KB
testcase_15 AC 224 ms
10,880 KB
testcase_16 AC 228 ms
11,264 KB
testcase_17 AC 226 ms
11,136 KB
testcase_18 AC 224 ms
11,136 KB
testcase_19 AC 226 ms
11,136 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using i64 = int64_t;
using vi = vector<i64>;
using vvi = vector<vi>;

vvi adj;

int main() {
    int n;
    cin >> n;
    adj = vvi(n);
    for (int i = 0; i < n - 1; i++) {
        int a, b;
        cin >> a >> b;
        a--;
        b--;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    vi rootdist(n, 1e9);
    queue<int> que;
    que.push(0);
    rootdist[0] = 0;
    while (que.size()) {
        int t = que.front();
        que.pop();
        for (int s: adj[t]) {
            if (rootdist[s] > rootdist[t] + 1) {
                rootdist[s] = rootdist[t] + 1;
                que.push(s);
            }
        }
    }

    vi leafdist(n, 1e9);
    for (int i = 1; i < n; i++) {
        if (adj[i].size() == 1) {
            que.push(i);
            leafdist[i] = 0;
        }
    }

    while (que.size()) {
        int t = que.front();
        que.pop();
        for (int s: adj[t]) {
            if (leafdist[s] > leafdist[t] + 1) {
                leafdist[s] = leafdist[t] + 1;
                que.push(s);
            }
        }
    }

    for (int i = 0; i < n; i++) {
        cout << min(rootdist[i], leafdist[i]) << endl;
    }    
}
0