bzoj1724: [Usaco2006 Nov]Fence Repair 切割木板
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 using namespace std; 7 int n,a; 8 typedef long long ll; 9 ll ans; 10 void read(int &x){ 11 x=0; int f=1; char ch; 12 for (ch=getchar();!isdigit(ch);ch=getchar()) if (ch=='-') f=-1; 13 for (;isdigit(ch);ch=getchar()) x=x*10+ch-'0'; x*=f; 14 } 15 priority_queue< int,vector<int>,greater<int> >heap; 16 int main(){ 17 read(n),ans=0; 18 for (int i=1;i<=n;i++) read(a),heap.push(a); 19 for (int x,y,i=1;i<n;i++){ 20 x=heap.top(),heap.pop(); 21 y=heap.top(),heap.pop(); 22 ans+=x+y; heap.push(x+y); 23 } 24 printf("%lld\n",ans); 25 return 0; 26 }
做法:堆入门题,学习系统堆的用法——>雾(:
大根堆:priority_queue<int>heap;
小根堆:priority_queue< int,vector<int>,greater<int> >heap;
heap.top() 函数:堆顶的元素值;
heap.pop()过程:弹出堆顶元素;
heap.empty()函数:堆空与否,堆空则返回1,否则返回0;
heap.push()过程:在堆中加入一个元素,并维护堆的性质。