結果

問題 No.277 根掘り葉掘り
ユーザー ふーらくたるふーらくたる
提出日時 2016-07-11 20:52:06
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 85 ms / 3,000 ms
コード長 1,480 bytes
コンパイル時間 544 ms
コンパイル使用メモリ 47,616 KB
実行使用メモリ 11,624 KB
最終ジャッジ日時 2024-04-21 12:52:35
合計ジャッジ時間 2,577 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 5 ms
6,272 KB
testcase_01 AC 4 ms
6,272 KB
testcase_02 AC 5 ms
6,272 KB
testcase_03 AC 5 ms
6,272 KB
testcase_04 AC 5 ms
6,144 KB
testcase_05 AC 5 ms
6,016 KB
testcase_06 AC 5 ms
6,272 KB
testcase_07 AC 5 ms
6,272 KB
testcase_08 AC 5 ms
6,144 KB
testcase_09 AC 85 ms
10,368 KB
testcase_10 AC 70 ms
11,624 KB
testcase_11 AC 67 ms
10,880 KB
testcase_12 AC 75 ms
10,880 KB
testcase_13 AC 75 ms
11,136 KB
testcase_14 AC 77 ms
11,204 KB
testcase_15 AC 74 ms
10,732 KB
testcase_16 AC 72 ms
10,856 KB
testcase_17 AC 72 ms
11,044 KB
testcase_18 AC 70 ms
10,732 KB
testcase_19 AC 75 ms
10,752 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:65:10: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   65 |     scanf("%d", &N);
      |     ~~~~~^~~~~~~~~~
main.cpp:68:14: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   68 |         scanf("%d%d", &x[i], &y[i]);
      |         ~~~~~^~~~~~~~~~~~~~~~~~~~~~

ソースコード

diff #

#include <cstdio>
#include <cstring>
#include <vector>
#include <utility>
#include <queue>
using namespace std;

typedef pair<int, int> P;

const int kMAX_N = 100010;

int dim[kMAX_N];
int x[kMAX_N - 1], y[kMAX_N - 1];

int R[kMAX_N], L[kMAX_N];

int N;

vector<int> graph[kMAX_N];

void BFS(int start, int init, int cost[]) {
    fill(cost, cost + kMAX_N, -1);

    queue<P> que;   // (頂点, 距離)
    cost[start] = init;
    que.push(P(start, init));
    while (!que.empty()) {
        P node = que.front(); que.pop();
        for (int i = 0; i < graph[node.first].size(); i++) {
            int to = graph[node.first][i];
            if (cost[to] < 0) {
                cost[to] = node.second + 1;
                que.push(P(to, cost[to]));
            }
        }
    }
}

void Solve() {
    for (int i = 0; i < N - 1; i++) {
        graph[x[i] - 1].push_back(y[i] - 1);
        graph[y[i] - 1].push_back(x[i] - 1);

        dim[x[i] - 1]++; dim[y[i] - 1]++;
    }

    int stab = N;
    for (int i = 0; i < N; i++) {
        if (i != 0 && dim[i] == 1) {    // 葉
            graph[i].push_back(stab);
            graph[stab].push_back(i);
        }
    }
    
    // 根とスタブから幅優先
    BFS(0, 0, R);
    BFS(stab, -1, L);

    for (int i = 0; i < N; i++) {
        printf("%d\n", min(R[i], L[i]));
    }
}

int main() {
    scanf("%d", &N);

    for (int i = 0; i < N - 1; i++) {
        scanf("%d%d", &x[i], &y[i]);
    }

    Solve();

    return 0;
}
0