結果

問題 No.806 木を道に
ユーザー tsuchinagatsuchinaga
提出日時 2019-04-24 13:32:23
言語 Go
(1.22.1)
結果
AC  
実行時間 31 ms / 2,000 ms
コード長 1,304 bytes
コンパイル時間 12,638 ms
コンパイル使用メモリ 234,456 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-25 08:24:33
合計ジャッジ時間 13,925 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 1 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 4 ms
5,376 KB
testcase_11 AC 4 ms
5,376 KB
testcase_12 AC 15 ms
5,376 KB
testcase_13 AC 11 ms
5,376 KB
testcase_14 AC 13 ms
5,376 KB
testcase_15 AC 15 ms
5,376 KB
testcase_16 AC 6 ms
5,376 KB
testcase_17 AC 13 ms
5,376 KB
testcase_18 AC 2 ms
5,376 KB
testcase_19 AC 5 ms
5,376 KB
testcase_20 AC 12 ms
5,376 KB
testcase_21 AC 7 ms
5,376 KB
testcase_22 AC 17 ms
5,376 KB
testcase_23 AC 16 ms
5,376 KB
testcase_24 AC 8 ms
5,376 KB
testcase_25 AC 12 ms
5,376 KB
testcase_26 AC 11 ms
5,376 KB
testcase_27 AC 31 ms
5,376 KB
testcase_28 AC 1 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
			}
		}
		d := int(math.Min(float64(branches[max]), float64(branches[min])))
		// fmt.Println(branches[max], branches[min], d)

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

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

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