結果

問題 No.277 根掘り葉掘り
ユーザー hama_duhama_du
提出日時 2015-11-20 19:13:20
言語 Go
(1.18)
結果
AC  
実行時間 219 ms / 3,000 ms
コード長 1,998 bytes
コンパイル時間 319 ms
使用メモリ 36,780 KB
最終ジャッジ日時 2022-12-03 17:31:22
合計ジャッジ時間 3,992 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
使用メモリ
testcase_00 AC 2 ms
5,384 KB
testcase_01 AC 2 ms
5,380 KB
testcase_02 AC 1 ms
5,384 KB
testcase_03 AC 2 ms
6,948 KB
testcase_04 AC 2 ms
5,380 KB
testcase_05 AC 2 ms
7,416 KB
testcase_06 AC 2 ms
7,416 KB
testcase_07 AC 2 ms
5,384 KB
testcase_08 AC 2 ms
5,384 KB
testcase_09 AC 219 ms
36,780 KB
testcase_10 AC 165 ms
18,696 KB
testcase_11 AC 178 ms
18,736 KB
testcase_12 AC 190 ms
22,936 KB
testcase_13 AC 174 ms
20,380 KB
testcase_14 AC 178 ms
18,800 KB
testcase_15 AC 182 ms
18,788 KB
testcase_16 AC 181 ms
18,796 KB
testcase_17 AC 182 ms
18,800 KB
testcase_18 AC 184 ms
18,820 KB
testcase_19 AC 184 ms
18,792 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	"io"
)

var depth []int
var rdepth []int
var graph [][]int
const INF = 114514

func dfs(now, par, dep int) int {
	depth[now] = dep
	min := INF
	for i := 0 ; i < len(graph[now]) ; i++ {
		to := graph[now][i]
		if to == par {
			continue
		}
		cn := dfs(to, now, dep+1) + 1
		if min > cn {
			min = cn
		}
	}
	if min == INF {
		min = 0
	}
	rdepth[now] = min
	return min
}

func dfs2(now, par int) {
	if par >= 0 && rdepth[now] > rdepth[par] + 1 {
		rdepth[now] = rdepth[par] + 1
	}
	for i := 0 ; i < len(graph[now]) ; i++ {
		to := graph[now][i]
		if to == par {
			continue
		}
		dfs2(to, now)
	}
}

func main() {
	n := nextInt()
	edges := make([][]int, n-1)
	deg := make([]int, n)
	for i := 0 ; i < n-1 ; i++ {
		edges[i] = make([]int, 2)
		a := nextInt()-1
		b := nextInt()-1
		deg[a]++
		deg[b]++
		edges[i][0] = a
		edges[i][1] = b
	}
	graph = make([][]int, n)
	for i := 0 ; i < n ; i++ {
		graph[i] = make([]int, deg[i])
	}
	for i := 0 ; i < n-1 ; i++ {
		a := edges[i][0]
		b := edges[i][1]
		deg[a]--
		deg[b]--
		graph[a][deg[a]] = b
		graph[b][deg[b]] = a
	}

	depth = make([]int, n)
	rdepth = make([]int, n)
	dfs(0, -1, 0)
	dfs2(0, -1)

	for i := 0 ; i < n ; i++ {
		if depth[i] < rdepth[i] {
			fmt.Println(depth[i])
		} else {
			fmt.Println(rdepth[i])
		}
	}
}

// ====

var rdr = bufio.NewReader(os.Stdin)

func nextInt() int {
	i, e := strconv.Atoi(readToken(20))
	if e != nil {
		panic(e)
	}
	return i
}

func nextString(limit int) string {
	return readToken(limit)
}

func readToken(limit int) string {
	buf := make([]byte, 0, limit)

	for {
		byte, err := rdr.ReadByte()
		if err != nil {
			if err == io.EOF {
				break
			}
		}
		if byte != 10 && byte != 13 && byte != 32 {
			buf = append(buf, byte)
			break
		}
	}
	for {
		byte, err := rdr.ReadByte()
		if err != nil {
			if err == io.EOF {
				break
			}
		}
		if byte == 10 || byte == 13 || byte == 32 {
			break
		}
		buf = append(buf, byte)
	}
	return string(buf)
}
0