結果

問題 No.806 木を道に
ユーザー tsuchinagatsuchinaga
提出日時 2019-04-24 13:28:37
言語 Go
(1.22.1)
結果
AC  
実行時間 31 ms / 2,000 ms
コード長 1,170 bytes
コンパイル時間 15,512 ms
コンパイル使用メモリ 233,728 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-25 08:16:49
合計ジャッジ時間 14,350 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 AC 1 ms
5,376 KB
testcase_04 AC 1 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 1 ms
5,376 KB
testcase_07 AC 1 ms
5,376 KB
testcase_08 AC 2 ms
5,376 KB
testcase_09 AC 1 ms
5,376 KB
testcase_10 AC 6 ms
5,376 KB
testcase_11 AC 5 ms
5,376 KB
testcase_12 AC 19 ms
5,376 KB
testcase_13 AC 14 ms
5,376 KB
testcase_14 AC 18 ms
5,376 KB
testcase_15 AC 19 ms
5,376 KB
testcase_16 AC 7 ms
5,376 KB
testcase_17 AC 16 ms
5,376 KB
testcase_18 AC 2 ms
5,376 KB
testcase_19 AC 6 ms
5,376 KB
testcase_20 AC 17 ms
5,376 KB
testcase_21 AC 10 ms
5,376 KB
testcase_22 AC 22 ms
5,376 KB
testcase_23 AC 23 ms
5,376 KB
testcase_24 AC 8 ms
5,376 KB
testcase_25 AC 12 ms
5,376 KB
testcase_26 AC 9 ms
5,376 KB
testcase_27 AC 31 ms
5,376 KB
testcase_28 AC 2 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

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

func main() {
	var n, a, b int
	_, _ = fmt.Scan(&n)

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	nodes := make([]int, n)
	for i := 0; i < n-1; i++ {
		sc.Scan()
		a, _ = strconv.Atoi(sc.Text())
		sc.Scan()
		b, _ = strconv.Atoi(sc.Text())

		nodes[a-1]++
		nodes[b-1]++
	}

	// fmt.Println(nodes)

	// 各ノードが持つ枝の数が分かったので、枝の数で集計しなおす
	branches := make(map[int]int)
	for _, n := range nodes {
		branches[n]++
	}

	// fmt.Println(branches)

	// 1: 2, 2: n-2 になるまで一番大きいのと一番小さいのから減らして、その隣に加算する作業をする
	ans := 0
	for {
		if branches[1] == 2 && branches[2] == n-2 {
			break
		}

		max := 0
		min := math.MaxInt64
		for b := range branches {
			if max < b {
				max = b
			}
			if min > b {
				min = b
			}
		}

		branches[max]--
		branches[max-1]++
		branches[min+1]++
		branches[min]--

		if branches[max] == 0 {
			delete(branches, max)
		}
		if branches[min] == 0 {
			delete(branches, min)
		}

		ans++
		// fmt.Println(ans, branches)
	}
	fmt.Println(ans)
}
0