結果
問題 | No.277 根掘り葉掘り |
ユーザー |
![]() |
提出日時 | 2015-07-14 02:42:59 |
言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
結果 |
AC
|
実行時間 | 198 ms / 3,000 ms |
コード長 | 1,054 bytes |
コンパイル時間 | 655 ms |
コンパイル使用メモリ | 70,128 KB |
実行使用メモリ | 16,896 KB |
最終ジャッジ日時 | 2024-07-08 07:05:57 |
合計ジャッジ時間 | 3,614 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 18 |
ソースコード
#include <iostream> #include <vector> #include <queue> using namespace std; const int INF = 1e8; void dfs(vector<vector<int>>& G, int pos, int last, vector<int>& leaf){ bool has_child = false; for(int i=0; i<G[pos].size(); i++){ if(G[pos][i] == last) continue; dfs(G, G[pos][i], pos, leaf); has_child = true; } if(has_child == false && pos != 0) leaf.push_back(pos); } int main(){ int n; cin >> n; vector<vector<int>> G(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); } vector<int> leaf; dfs(G, 0, -1, leaf); vector<int> dist(n, INF); queue<pair<int,int>> q; q.push({0,0}); dist[0] = 0; for(int i=0; i<leaf.size(); i++){ q.push({leaf[i], 0}); dist[leaf[i]] = 0; } while(q.size()){ int pos = q.front().first; int d = q.front().second; q.pop(); for(int i=0; i<G[pos].size(); i++){ if(dist[G[pos][i]] > d+1){ dist[G[pos][i]] = d+1; q.push({G[pos][i], d+1}); } } } for(int i=0; i<n; i++){ cout << dist[i] << endl; } return 0; }