标签:http 输出 output pop i++ queue span desc ext
3 1 2 9
15
水题,熟悉堆
//堆排序
#include<cstdio>
#include<iostream>
using namespace std;
int a[10010],asize,n;
void put(int x)
{
a[++asize]=x;
int next,now=asize;
while(now>1)
{
next=now/2;
if(a[next]>a[now])
swap(a[next],a[now]);
now=next;
}
}
int gets()
{
int ret = a[1];
a[1]=a[asize--];
int now=1;
while(now*2<=asize)
{
int next = now*2;
if(next<asize&&a[next]>a[next+1])next++;
if(a[next]<a[now])swap(a[next],a[now]);
now=next;
}
return ret;
}
int main()
{
int n;
while(cin>>n)
{ int x;
asize=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
put(x);
}
int ans=0;
while(asize>1)
{
x=gets();
x+=gets();
put(x);
//cout<<x<<" ";
ans+=x;
}
cout<<ans<<endl;
}
return 0;
}
//优先队列
#include<iostream>
#include<queue>
using namespace std;
int n;
priority_queue<int ,vector<int>,greater<int> >h; //优先队列
int main()
{
while(cin>>n)
{ int x,ans=0,y;
for(int i=1;i<=n;i++)
{ cin>>x;
h.push(x);
}
for(int i=1;i<n;i++)
{
x=h.top();h.pop();
y=h.top();h.pop();
x+=y;
ans+=x;
h.push(x);
}
h.pop();
cout<<ans<<endl;
}
return 0;
}
标签:http 输出 output pop i++ queue span desc ext
原文地址:http://www.cnblogs.com/552059511wz/p/6657750.html