結果

問題 No.277 根掘り葉掘り
ユーザー snrnsidysnrnsidy
提出日時 2021-07-18 23:45:15
言語 C++17
(gcc 11.2.0 + boost 1.78.0)
結果
AC  
実行時間 90 ms / 3,000 ms
コード長 1,304 bytes
コンパイル時間 2,034 ms
使用メモリ 25,424 KB
最終ジャッジ日時 2023-02-12 10:22:59
合計ジャッジ時間 4,489 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
使用メモリ
testcase_00 AC 4 ms
6,224 KB
testcase_01 AC 3 ms
6,132 KB
testcase_02 AC 4 ms
6,136 KB
testcase_03 AC 4 ms
6,104 KB
testcase_04 AC 4 ms
6,196 KB
testcase_05 AC 4 ms
6,156 KB
testcase_06 AC 4 ms
6,248 KB
testcase_07 AC 4 ms
6,204 KB
testcase_08 AC 4 ms
6,180 KB
testcase_09 AC 90 ms
25,424 KB
testcase_10 AC 76 ms
14,328 KB
testcase_11 AC 59 ms
9,720 KB
testcase_12 AC 84 ms
19,824 KB
testcase_13 AC 76 ms
9,796 KB
testcase_14 AC 74 ms
10,980 KB
testcase_15 AC 73 ms
11,532 KB
testcase_16 AC 72 ms
10,664 KB
testcase_17 AC 70 ms
10,544 KB
testcase_18 AC 67 ms
10,176 KB
testcase_19 AC 68 ms
10,036 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

int R[100005];
int L[100005];
vector <int> adj[100005];
int n, x, y;

void dfs(int now,int prev)
{
	for (auto next : adj[now])
	{
		if (prev == next) continue;
		R[next] = R[now] + 1;
		dfs(next, now);
	}
}

int solve(int now, int prev)
{
	if (L[now] != -1)
	{
		return L[now];
	}
	int res = 1e9;
	for (auto next : adj[now])
	{
		if (prev == next)
		{
			continue;
		}
		res = min(res, solve(next, now) + 1);
	}
	if (res >= 1e9)
	{
		res = 0;
	}
	L[now] = res;
	return L[now];
}

void dfs2(int now, int prev, int U)
{
	multiset <int> S;
	L[now] = min(L[now], U);
	for (auto next : adj[now])
	{
		if (next == prev) continue;
		S.insert(L[next] + 1);
	}
	for (auto next : adj[now])
	{
		if (prev == next) continue;
		S.erase(L[next] + 1);
		if (!S.empty())
		{
			int MIN = *S.begin();
			MIN = min(MIN, U);
			dfs2(next, now, MIN + 1);
		}
		else
		{
			dfs2(next, now, U + 1);
		}
		S.insert(L[next] + 1);
	}
}
int main(void)
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	
	cin >> n;

	for (int i = 0; i < n - 1; i++)
	{
		cin >> x >> y;
		adj[x].push_back(y);
		adj[y].push_back(x);
	}

	memset(L, -1, sizeof(L));
	R[1] = 0;
	dfs(1, 0);
	solve(1, 0);
	dfs2(1, 0, 1e9);
	for (int i = 1; i <= n; i++)
	{
		cout << min(L[i], R[i]) << '\n';
	}


	return 0;
}
0