結果

問題 No.277 根掘り葉掘り
ユーザー imulanimulan
提出日時 2016-03-06 22:46:17
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 53 ms / 3,000 ms
コード長 1,240 bytes
コンパイル時間 1,276 ms
コンパイル使用メモリ 166,464 KB
実行使用メモリ 10,600 KB
最終ジャッジ日時 2023-10-24 20:10:00
合計ジャッジ時間 3,574 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
7,056 KB
testcase_01 AC 3 ms
7,056 KB
testcase_02 AC 4 ms
7,056 KB
testcase_03 AC 3 ms
7,056 KB
testcase_04 AC 4 ms
7,060 KB
testcase_05 AC 3 ms
7,056 KB
testcase_06 AC 4 ms
7,056 KB
testcase_07 AC 3 ms
7,060 KB
testcase_08 AC 4 ms
7,056 KB
testcase_09 AC 51 ms
10,180 KB
testcase_10 AC 39 ms
10,600 KB
testcase_11 AC 49 ms
10,388 KB
testcase_12 AC 49 ms
10,392 KB
testcase_13 AC 53 ms
10,572 KB
testcase_14 AC 52 ms
10,460 KB
testcase_15 AC 52 ms
10,452 KB
testcase_16 AC 51 ms
10,400 KB
testcase_17 AC 50 ms
10,532 KB
testcase_18 AC 50 ms
10,456 KB
testcase_19 AC 50 ms
10,468 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:22:14: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   22 |         scanf(" %d",&n);
      |         ~~~~~^~~~~~~~~~
main.cpp:26:22: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   26 |                 scanf(" %d %d",&x,&y);
      |                 ~~~~~^~~~~~~~~~~~~~~~

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define rep(i,n) for(i=0;i<n;++i)
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define mp make_pair
#define pb push_back
#define fi first
#define sc second

const int N=100000;
const int INF=12345678;

vector<int> G[N];

int main()
{
	int i;

	int n;
	scanf(" %d",&n);
	rep(i,n-1)
	{
		int x,y;
		scanf(" %d %d",&x,&y);
		--x;
		--y;
		G[x].pb(y);
		G[y].pb(x);
	}

	int r[N],l[N];
	fill(r,r+n,INF);
	fill(l,l+n,INF);

	bool leaf[N];
	fill(leaf,leaf+n,false);

	queue<int> q;

	//まず根からBFS
	q.push(0);
	r[0]=0;
	while(!q.empty())
	{
		int v=q.front();
		q.pop();

		bool isLeaf=true;
		rep(i,G[v].size())
		{
			if(r[G[v][i]]>r[v]+1)
			{
				r[G[v][i]]=r[v]+1;
				q.push(G[v][i]);
				isLeaf=false;
			}
		}

		leaf[v]=isLeaf;
	}

	/*
	rep(i,n) printf(" r[%d] = %d\n",i,r[i]);
	rep(i,n) printf(" leaf[%d] = %d\n",i,leaf[i]);
	*/
	
	//次に葉からBFS
	rep(i,n)
	{
		if(leaf[i])
		{
			q.push(i);
			l[i]=0;
		}
	}
	while(!q.empty())
	{
		int v=q.front();
		q.pop();

		rep(i,G[v].size())
		{
			if(l[G[v][i]]>l[v]+1)
			{
				l[G[v][i]]=l[v]+1;
				q.push(G[v][i]);
			}
		}
	}

	rep(i,n) printf("%d\n", min(r[i],l[i]));
}
0