http://codevs.cn/problem/1063/
堆结构的上手测试题。
之前学堆的时候写过一个模板,直接拿过来用。
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; int heap[20010] , temp ,size , ans , n , a , b; void Insert(int x){ int curr = ++size; heap[size] = x; int parent = curr / 2; while(parent > 0 && heap[parent] > heap[curr]){ swap(heap[parent] , heap[curr]); curr = parent; parent = curr / 2; } } void Pop(){ heap[1] = heap[size--]; int curr = 1; int son = curr * 2; if(heap[son] > heap[son + 1])son++; while(son <= size && heap[son] < heap[curr]){ swap(heap[son] , heap[curr]); curr = son; son = curr * 2; if(heap[son] > heap[son + 1])son++; } }
每次把小根堆里最小的两个值Pop出来,再Insert二者的和,来模拟合并两堆果子。最后只剩一堆的时候停止。
主函数:
int main(){ cin >> n; for(int i = 1 ; i <= n ; i++){ cin >> temp; Insert(temp); } while(size > 1){ a = heap[1];Pop(); b = heap[1];Pop(); temp = a + b; Insert(temp); ans += temp; } cout << ans << endl; return 0; }
转载于:https://www.cnblogs.com/miserweyte/p/11134368.html