結果
問題 | No.277 根掘り葉掘り |
ユーザー |
|
提出日時 | 2021-03-17 13:16:13 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 175 ms / 3,000 ms |
コード長 | 1,042 bytes |
コンパイル時間 | 1,940 ms |
コンパイル使用メモリ | 198,072 KB |
最終ジャッジ日時 | 2025-01-19 17:53:25 |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 18 |
ソースコード
#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; }