結果

問題 No.277 根掘り葉掘り
ユーザー koyumeishikoyumeishi
提出日時 2015-07-14 02:42:59
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 221 ms / 3,000 ms
コード長 1,054 bytes
コンパイル時間 675 ms
コンパイル使用メモリ 69,880 KB
実行使用メモリ 15,248 KB
最終ジャッジ日時 2023-09-22 15:30:49
合計ジャッジ時間 4,304 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 2 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 221 ms
15,248 KB
testcase_10 AC 187 ms
10,388 KB
testcase_11 AC 212 ms
9,912 KB
testcase_12 AC 209 ms
12,608 KB
testcase_13 AC 215 ms
9,544 KB
testcase_14 AC 212 ms
10,120 KB
testcase_15 AC 215 ms
10,216 KB
testcase_16 AC 213 ms
9,900 KB
testcase_17 AC 212 ms
9,932 KB
testcase_18 AC 215 ms
9,828 KB
testcase_19 AC 213 ms
9,932 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#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;
}
0