AcWing 148. 合并果子
原题链接
简单
作者:
Sam_2
,
2020-10-05 07:31:53
,
所有人可见
,
阅读 592
package main
import(
"container/heap"
"fmt"
)
const N int = 100010
type HeapInt []int
func (h *HeapInt) Len() int {
return len(*h)
}
func (h *HeapInt) Less(i, j int) bool {
return (*h)[i] < (*h)[j]
}
func (h *HeapInt) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
func (h *HeapInt) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *HeapInt) Pop() interface{} {
tmpt := (*h)[len(*h)-1: len(*h)][0]
*h = (*h)[0: len(*h)-1]
return tmpt
}
func main() {
var n int
fmt.Scanf("%d", &n)
s := make([]int, n)
for i := 0; i < n; i++ {
fmt.Scanf("%d", &s[i])
}
heap.Init((*HeapInt)(&s))
res := 0
for len(s) >= 2 {
a := heap.Pop((*HeapInt)(&s)).(int)
b := heap.Pop((*HeapInt)(&s)).(int)
c := a + b
res += c
heap.Push((*HeapInt)(&s), c)
}
fmt.Printf("%d\n", res)
}