結果

問題 No.277 根掘り葉掘り
ユーザー kk
提出日時 2021-03-17 13:16:13
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 196 ms / 3,000 ms
コード長 1,042 bytes
コンパイル時間 2,392 ms
コンパイル使用メモリ 204,464 KB
実行使用メモリ 17,500 KB
最終ジャッジ日時 2023-08-09 09:08:11
合計ジャッジ時間 6,911 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
5,696 KB
testcase_01 AC 4 ms
5,784 KB
testcase_02 AC 3 ms
5,996 KB
testcase_03 AC 3 ms
5,924 KB
testcase_04 AC 3 ms
5,716 KB
testcase_05 AC 3 ms
5,832 KB
testcase_06 AC 3 ms
5,780 KB
testcase_07 AC 3 ms
5,688 KB
testcase_08 AC 3 ms
5,828 KB
testcase_09 AC 196 ms
17,500 KB
testcase_10 AC 163 ms
10,200 KB
testcase_11 AC 179 ms
9,860 KB
testcase_12 AC 183 ms
13,860 KB
testcase_13 AC 185 ms
10,208 KB
testcase_14 AC 177 ms
10,424 KB
testcase_15 AC 177 ms
11,052 KB
testcase_16 AC 176 ms
10,340 KB
testcase_17 AC 177 ms
10,220 KB
testcase_18 AC 177 ms
10,188 KB
testcase_19 AC 176 ms
10,140 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

const int INF = 1<<28;

int n;
vector<int> g[100000];
bool leaf[100000];
int root_dist[100000];
int leaf_dist[100000];

void dfs(int v, int d, int par = -1) {
  root_dist[v] = d;
  int chi = 0;
  for (int w : g[v]) {
    if (w == par)
      continue;
    dfs(w, d + 1, v);
    ++chi;
  }
  if (!chi)
    leaf[v] = true;
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);

  cin >> n;
  for (int i = 0; i < n-1; i++) {
    int x, y;
    cin >> x >> y;
    --x, --y;
    g[x].push_back(y);
    g[y].push_back(x);
  }

  dfs(0, 0);

  queue<int> q;
  fill(leaf_dist, leaf_dist + n, INF);
  for (int i = 0; i < n; i++) {
    if (leaf[i]) {
      q.push(i);
      leaf_dist[i] = 0;
    }
  }

  while (!q.empty()) {
    int v = q.front();
    q.pop();
    for (int w: g[v]) {
      if (leaf_dist[w] == INF) {
        q.push(w);
        leaf_dist[w] = leaf_dist[v] + 1;
      }
    }
  }

  for (int i = 0; i < n; i++)
    cout << min(root_dist[i], leaf_dist[i]) << endl;
  
  return 0;
}
0