卡常神器 手写堆

来源:互联网 发布:剑灵力士捏脸数据大全 编辑:程序博客网 时间:2024/05/17 19:15

跟gxy大神还有yzh大神学了学手写的堆,应该比stl的优先队列快很多。
其实就是维护了一个二叉堆,写进结构体里,就没啥了。。。
据说达哥去年NOIP靠这个暴力多骗了分

合并果子。。。。

#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <algorithm>#define N 10010using 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);}
原创粉丝点击