結果

問題 No.277 根掘り葉掘り
コンテスト
ユーザー bal4u
提出日時 2019-05-10 14:29:10
言語 C(gnu17)
(gcc 15.2.0)
コンパイル:
gcc-15 -O2 -std=gnu17 -Wno-error=implicit-function-declaration -Wno-error=implicit-int -Wno-error=incompatible-pointer-types -Wno-error=int-conversion -DONLINE_JUDGE -o a.out _filename_ -lm
実行:
./a.out
結果
AC  
実行時間 61 ms / 3,000 ms
コード長 1,383 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 236 ms
コンパイル使用メモリ 39,936 KB
最終ジャッジ日時 2026-02-22 03:20:13
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 18
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

// yukicoder: No.277 根掘り葉掘り
// 2019.5.10 bal4u

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if 1
#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)
#else
#define gc() getchar()
#define pc(c) putchar(c)
#endif
int in()
{
	int n = 0, c = gc();
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

void out(int n)
{
	int i;
	char ob[20];

	if (!n) pc('0');
	else {
		i = 0; while (n) ob[i++] = n%10 + '0', n/=10;
		while (i--) pc(ob[i]);
	}
	pc('\n');
}

#define MAX 100003
#define INF 0x33
int N;
int *to[MAX], hi[MAX];
int ans[MAX];

void dfs(int node, int par, int h) {
	int i;
	if (ans[node] > h) ans[node] = h;
	if (node && hi[node] == 1) {
		ans[node] = 0;
		if (ans[par] > 1) dfs(par, node, 1);
	} else {
		for (i = 0; i < hi[node]; i++) {
			if (ans[to[node][i]] > h+1) dfs(to[node][i], node, h+1);
		}
	}
}

int main()
{
	int i, x, y;
	int *memo, sz;
	
	N = in();
	memo = malloc(sizeof(int)*2*N);
	sz = 0; for (i = 1; i < N; i++) {
		memo[sz++] = x = in()-1, memo[sz++] = y = in()-1;
		hi[x]++, hi[y]++;
	}
	for (i = 0; i < N; i++) if (hi[i]) {
		to[i] = malloc(sizeof(int)*hi[i]);
	}
	memset(hi, 0, sizeof(int)*N);
	i = 0; while (i < sz) {
		x = memo[i++], y = memo[i++];
		to[x][hi[x]++] = y, to[y][hi[y]++] = x;
	}
	memset(ans, INF, sizeof(int)*N);
	dfs(0, -1, 0);
	for (i = 0; i < N; i++) out(ans[i]);
	return 0;
}
0