2.14
作者:互联网
哈夫曼树:
最小堆:
https://www.acwing.com/problem/content/150/
合并果子
拓展题:282,2889
c写法:
#include<iostream> using namespace std; const int N = 10010; int n; int heap[N]; void down(int x){ int t = x; if(2*x <= n && heap[2*x] < heap[t]) t = 2*x; if(2*x + 1 <= n && heap[2*x + 1] < heap[t]) t = 2*x + 1; if(heap[t] < heap[x]){ swap(heap[t], heap[x]); down(t); } } void up(int x){ while(x > 1 && heap[x/2] > heap[x]){ swap(heap[x], heap[x/2]); x >>= 1; } } int main(){ cin >> n; for(int i = 1; i <= n; i++) cin >> heap[i]; for(int i = n/2; i >= 1; i--) down(i); int res = 0; while(n > 1){ int a = heap[1]; heap[1] = heap[n--]; down(1); int b = heap[1]; heap[1] = heap[n--]; down(1); res += a + b; heap[++n] = a + b; up(n); } cout << res << endl; }View Code
c++写法:stl大法
#include<bits/stdc++.h> using namespace std; int n,ans,a[10001]; bool cmp(int x,int y){return x>y;} int main(){ cin>>n; for(int i=0;i<n;i++) cin>>a[i]; make_heap(a,a+n,cmp); for(int i=n;i>1;i--){ pop_heap(a,a+i,cmp); pop_heap(a,a+i-1,cmp); a[i-2]+=a[i-1]; ans+=a[i-2]; push_heap(a,a+i-1,cmp); } cout<<ans<<endl; return 0; }View Code
桶排+队列:
#include<bits/stdc++.h> using namespace std; int n,a,cnt[20009],Max; long long ans; queue<int> q1,q2; int main(){ cin>>n; for(int i=1;i<=n;++i){scanf("%d",&a);Max=max(a,Max),cnt[a]++;} for(int i=1;i<=Max;++i) while(cnt[i]--)q1.push(i); for(int i=1,x1,x2;i<n;++i){ if(q2.empty()||!q1.empty()&&q1.front()<q2.front()){x1=q1.front();q1.pop();}//我是个沙茶,之前把q1.empty()写成了q1.front() else{x1=q2.front();q2.pop();} if(q2.empty()||!q1.empty()&&q1.front()<q2.front()){x2=q1.front();q1.pop();} else{x2=q2.front();q2.pop();} q2.push(x1+x2);ans+=x1+x2; } cout<<ans<<endl; return 0; }View Code
标签:int,down,--,heap,ans,2.14,cmp 来源: https://www.cnblogs.com/chouhui/p/14401441.html