编辑
2024-09-17
算法题
00
请注意,本文编写于 235 天前,最后修改于 237 天前,其中某些信息可能已经过时。

今天做一道模板题,感觉题目答案都告诉你了

https://www.acwing.com/problem/content/150/

每次合并最小的两堆就可以

cpp
#include <iostream> #include <queue> #include <vector> using namespace std; int main() { int n; cin >> n; // 使用优先队列(最小堆)来存储果子堆 priority_queue<int, vector<int>, greater<int>> pq; // 读取每种果子的数目并加入优先队列 for (int i = 0; i < n; ++i) { int num; cin >> num; pq.push(num); } int total_cost = 0; // 每次合并最小的两堆,直到只剩下一个堆 while (pq.size() > 1) { // 取出最小的两堆 int first = pq.top(); pq.pop(); int second = pq.top(); pq.pop(); // 合并这两堆,并将合并后的堆加入优先队列 int new_pile = first + second; pq.push(new_pile); // 累加合并的体力消耗 total_cost += new_pile; } // 输出最小的体力耗费值 cout << total_cost << endl; return 0; }

Go版本

go
package main import ( "container/heap" "fmt" ) // 定义一个最小堆的接口 type MinHeap []int func (h MinHeap) Len() int { return len(h) } func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] } func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(int)) } func (h *MinHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } func main() { var n int fmt.Scan(&n) // 初始化最小堆 h := &MinHeap{} heap.Init(h) // 读取每种果子的数目并加入最小堆 for i := 0; i < n; i++ { var num int fmt.Scan(&num) heap.Push(h, num) } totalCost := 0 // 每次合并最小的两堆,直到只剩下一个堆 for h.Len() > 1 { // 取出最小的两堆 first := heap.Pop(h).(int) second := heap.Pop(h).(int) // 合并这两堆,并将合并后的堆加入最小堆 newPile := first + second heap.Push(h, newPile) // 累加合并的体力消耗 totalCost += newPile } // 输出最小的体力耗费值 fmt.Println(totalCost) }

最后是ruby

ruby
class MinHeap def initialize @heap = [] end def push(value) @heap << value heapify_up(@heap.size - 1) end def pop return nil if @heap.empty? swap(0, @heap.size - 1) min_value = @heap.pop heapify_down(0) min_value end private def parent(index) (index - 1) / 2 end def left_child(index) 2 * index + 1 end def right_child(index) 2 * index + 2 end def swap(i, j) @heap[i], @heap[j] = @heap[j], @heap[i] end def heapify_up(index) while index > 0 && @heap[parent(index)] > @heap[index] swap(index, parent(index)) index = parent(index) end end def heapify_down(index) loop do left = left_child(index) right = right_child(index) smallest = index smallest = left if left < @heap.size && @heap[left] < @heap[index] smallest = right if right < @heap.size && @heap[right] < @heap[smallest] break if smallest == index swap(index, smallest) index = smallest end end end def min_cost_to_merge_fruits(n, fruits) heap = MinHeap.new fruits.each { |fruit| heap.push(fruit) } total_cost = 0 while heap.size > 1 first = heap.pop second = heap.pop new_pile = first + second total_cost += new_pile heap.push(new_pile) end total_cost end # 读取输入 n = gets.to_i fruits = gets.split.map(&:to_i) # 计算并输出最小的体力耗费值 puts min_cost_to_merge_fruits(n, fruits)

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!