题解 | 分金条的最小花费

分金条的最小花费

https://www.nowcoder.com/practice/418d2fcdf7f24d6f8f4202e23951c0da

package main

import (
	"container/heap"
	"fmt"
)

type Myheap []int
func (m Myheap) Len() int {return len(m)}
func (m Myheap) Swap(i,j int) {m[i], m[j] = m[j], m[i]}
func (m Myheap) Less(i,j int) bool {return m[i]<m[j]}

func (m *Myheap) Push(x interface{}) {
    *m = append(*m, x.(int))
}
func (m *Myheap) Pop() interface{} {
    x := (*m)[len(*m)-1]
    *m = (*m)[:len(*m)-1]
    return x
}
// 贪心策略求解,将整个拆分过程逆向分为合成过程
// 每次将最小的合成,操作次数降到最低,使得最后的成本最小。
func main() {
    num := 0
    for {
        n, _ := fmt.Scan(&num)
        if n == 0 {
            break
        } else {
            arr := make([]int, num)
            for i:=0; i<len(arr); i++ {
                fmt.Scan(&arr[i])
            }

            var myheap Myheap
            for i:=0; i<len(arr); i++ {
                myheap = append(myheap, arr[i])
            }
            heap.Init(&myheap)
            cost := 0
            for len(myheap) > 1 {
                f1 := (heap.Pop(&myheap)).(int)
                f2 := (heap.Pop(&myheap)).(int)
                costsub := f1+f2
                heap.Push(&myheap, costsub)
                cost += costsub
            }
            fmt.Println(cost)
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
2025-12-04 17:00
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务