結果

問題 No.277 根掘り葉掘り
ユーザー xuzijian629xuzijian629
提出日時 2018-10-30 16:28:44
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 229 ms / 3,000 ms
コード長 1,217 bytes
コンパイル時間 2,643 ms
コンパイル使用メモリ 208,620 KB
実行使用メモリ 11,888 KB
最終ジャッジ日時 2023-08-12 10:30:01
合計ジャッジ時間 6,801 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 223 ms
10,240 KB
testcase_10 AC 196 ms
11,256 KB
testcase_11 AC 224 ms
11,888 KB
testcase_12 AC 219 ms
10,920 KB
testcase_13 AC 229 ms
10,924 KB
testcase_14 AC 219 ms
10,980 KB
testcase_15 AC 226 ms
11,284 KB
testcase_16 AC 221 ms
11,040 KB
testcase_17 AC 218 ms
11,020 KB
testcase_18 AC 219 ms
11,096 KB
testcase_19 AC 220 ms
11,240 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