結果

問題 No.277 根掘り葉掘り
ユーザー hanorverhanorver
提出日時 2015-09-04 23:48:08
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,233 bytes
コンパイル時間 809 ms
コンパイル使用メモリ 71,348 KB
実行使用メモリ 9,084 KB
最終ジャッジ日時 2023-09-26 07:20:35
合計ジャッジ時間 3,828 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 WA -
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 WA -
testcase_08 AC 2 ms
4,380 KB
testcase_09 WA -
testcase_10 AC 171 ms
7,768 KB
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 -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>

struct tree {
	std::vector<int> child;
	int dist_root;
	int dist_leaf;
	int parent;
};

int main() {
	int n;
	std::cin >> n;

	std::vector<tree> v(n);
	for (int i = 0; i < n - 1; i++) {
		int from, to;
		std::cin >> from >> to;
		v[from - 1].child.push_back(to - 1);
	}

	std::stack<int> s, leafpoint;
	s.push(0);
	v[0].dist_root = 0;
	int dist = 1;
	while (!s.empty()) {
		int node = s.top();
		s.pop();
		for (int i = 0; i < v[node].child.size(); i++) {
			v[v[node].child[i]].dist_root = v[node].dist_root + 1;
			v[v[node].child[i]].parent = node;
			s.push(v[node].child[i]);
		}
		v[node].dist_leaf = 99999;
		if (v[node].child.size() == 0)leafpoint.push(node);
	}

	std::stack<int> parent;
	while (!leafpoint.empty()) {
		int node = leafpoint.top();
		leafpoint.pop();
		v[node].dist_leaf = 0;
		parent.push(v[node].parent);
		int dist = 1;
		while (!parent.empty()) {
			int pa = parent.top();
			parent.pop();
			v[pa].dist_leaf = std::min(v[pa].dist_leaf, dist);
			if (pa == 0)break;
			parent.push(v[pa].parent);
			dist++;
		}
	}

	for (int i = 0; i < n; i++) {
		std::cout << std::min(v[i].dist_root, v[i].dist_leaf) << std::endl;
	}
	return 0;
}
0