分析:
找最小的加入堆
s t l C o d e : stl~Code: stl Code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define reg register
using namespace std;
typedef long long ll;
int n,ans;
priority_queue<int,vector<int>,greater<int> > q;
int main(){
scanf("%d",&n);
for(int i=1,x;i<=n;i++)
{
scanf("%d",&x);
q.push(x);
}
while(q.size()>=2)
{
int x=q.top(); q.pop();
int y=q.top(); q.pop();
ans+=x+y;
q.push(x+y);
}
printf("%d",ans);
return 0;
}
手打堆 C o d e : Code: Code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define reg register
using namespace std;
typedef long long ll;
const int N=1e4+5;
int n,ans,a[N],tot;
namespace Heap{
void down(int x)
{
while((x<<1)<=tot&&a[x]>a[x<<1]||(x<<1|1)<=tot&&a[x]>a[x<<1|1])
{
int son=x<<1;
if(son+1<=tot&&a[son+1]<a[son]) son++;
swap(a[x],a[son]);
x=son;
}
}
void up(int x)
{
while(x&&a[x]<a[x>>1])
{
swap(a[x],a[x>>1]);
x>>=1;
}
}
void push(int x)
{
a[++tot]=x;
up(tot);
}
void pop(int x)
{
if(a[x]<a[tot]) a[x]=a[tot--],down(x);
else a[x]=a[tot--],up(x);
}
}
int main(){
scanf("%d",&n);
for(int i=1,x;i<=n;i++)
{
scanf("%d",&x);
Heap::push(x);
}
while(tot>=2)
{
int x=a[1]; Heap::pop(1);
int y=a[1]; Heap::pop(1);
ans+=x+y;
Heap::push(x+y);
}
printf("%d",ans);
return 0;
}