bzoj 1724: [Usaco2006 Nov]Fence Repair 切割木板【堆】

时间:2023-03-09 08:29:48
bzoj 1724: [Usaco2006 Nov]Fence Repair 切割木板【堆】

如果反着看,看成合并木板,就和合并果子一样了,把若干块放进一个小根堆,然后每次取出两个合并,把合并结果加进答案和堆里

代码里小根堆用优先队列实现(懒

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int N=20005;
int n;
priority_queue<int,vector<int>,greater<int> >q;
int read()
{
int r=0,f=1;
char p=getchar();
while(p>'9'||p<'0')
{
if(p=='-')
f=-1;
p=getchar();
}
while(p>='0'&&p<='9')
{
r=r*10+p-48;
p=getchar();
}
return r*f;
}
int main()
{
n=read();
for(int i=1;i<=n;i++)
{
int x=read();
q.push(x);
}
long long ans=0;
while(q.size()>1)
{
int a=q.top();q.pop();
int b=q.top();q.pop();
ans+=a+b;
q.push(a+b);
}
printf("%lld\n",ans);
return 0;
}