結果

問題 No.277 根掘り葉掘り
ユーザー srup٩(๑`н´๑)۶srup٩(๑`н´๑)۶
提出日時 2016-09-16 10:49:06
言語 C++11
(gcc 11.4.0)
結果
TLE  
実行時間 -
コード長 1,336 bytes
コンパイル時間 862 ms
コンパイル使用メモリ 68,820 KB
実行使用メモリ 18,044 KB
最終ジャッジ日時 2024-04-28 14:01:38
合計ジャッジ時間 5,406 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
11,392 KB
testcase_01 AC 3 ms
5,888 KB
testcase_02 AC 3 ms
6,016 KB
testcase_03 AC 2 ms
5,888 KB
testcase_04 AC 3 ms
5,888 KB
testcase_05 AC 3 ms
6,016 KB
testcase_06 AC 2 ms
6,144 KB
testcase_07 AC 3 ms
5,888 KB
testcase_08 AC 3 ms
6,016 KB
testcase_09 AC 89 ms
9,984 KB
testcase_10 TLE -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int i=0;i<(n);i++)

const int INF = 1e9;
int n, x[100010], y[100010];
vector<int> G[100010];
int dist1[100010], dist2[100010];

int main(void){
	cin >> n;
	rep(i, n - 1){
		int tx, ty; cin >> tx >> ty;
		tx--; ty--;
		G[tx].push_back(ty); G[ty].push_back(tx);
	}

	//葉のノード
	vector<int> ha;
	rep(i, n){
		if(G[i].size() == 1 && i != 0) ha.push_back(i);
	}

	rep(i, n) dist1[i] = dist2[i] = INF;

	//根->葉へ
	queue<pair<int, int> > q;
	q.push(make_pair(0, -1));
	dist1[0] = 0;
	while(!q.empty()){
		int u = q.front().first;
		int p = q.front().second;
		q.pop();
		for(auto v : G[u]){
			if(v != p && dist1[v] == INF){//戻るの禁止と一度調べたところはもう最短で調べ済み
				dist1[v] = min(dist1[v], dist1[u] + 1);
				q.push(make_pair(v, u));
			}
		}
	}

	//葉->根
	for(auto start : ha){
		queue<pair<int, int> > q;
		q.push(make_pair(start, -1));
		dist2[start] = 0;
		while(!q.empty()){
			int u = q.front().first;
			int p = q.front().second;
			q.pop();
			for(auto v : G[u]){
				if(v != p){
					dist2[v] = min(dist2[v], dist2[u] + 1);
					q.push(make_pair(v, u));
				}
			}
		}
	}

	rep(i, n){
		printf("%d\n", min(dist1[i], dist2[i]));
	}
	return 0;
}
0