卡常神器 手寫堆
阿新 • • 發佈:2019-02-09
跟gxy大神還有yzh大神學了學手寫的堆,應該比stl的優先佇列快很多。
其實就是維護了一個二叉堆,寫進結構體裡,就沒啥了。。。
據說達哥去年NOIP靠這個暴力多騙了分
合併果子。。。。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 10010
using namespace std;
int read()
{
int sum=0,f=1;char x=getchar();
while (x<'0'||x>'9')f=(x=='-')?-1:1,x=getchar();
while(x>='0'&&x<='9')sum=(sum<<3)+(sum<<1)+x-'0',x=getchar();
return sum*f;
}
int n,ans;
template <class qty> struct dui
{
qty q[N];int sz;
dui(){sz=0;}
inline void push(int x)
{
q[++sz]=x;
for (int i=sz,j=i>>1;j;i=j,j>>=1)
if(q[j]>q[i])swap(q[j],q[i]);
}
inline void pop()
{
q[1]=q[sz--];
for(int i=1,j=i<<1;j<=sz;i=j,j<<=1)
{
if((j|1)<=sz&&q[j|1]<q[j])j=j|1;
if(q[i]>q[j])swap(q[i] ,q[j]);
else break;
}
}
inline qty top(){return q[1];}
};
dui<int> q;
int main()
{
n=read();
for(int i=1,x;i<=n;i++)
{
x=read();
q.push(x);
}
int x,y;
while(q.sz!=1)
{
x=q.top();q.pop();
y=q.top();q.pop();
ans+=x+y;
q.push(x+y);
}
printf("%d",ans);
}