結果

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

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
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 -
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:66:10: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   66 |     scanf("%d", &N);
      |     ~~~~~^~~~~~~~~~
main.cpp:69:14: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   69 |         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++) {
        printf("i %d\n", 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