bzoj 1724: [Usaco2006 Nov]Fence Repair cut wood planks [heap]

If you look at it backwards, it is regarded as merging boards, which is the same as merging fruits. Put several blocks into a small root pile, and then take out two merges at a time, and add the combined results to the answer and
the small root pile in the code in the heap. Priority queue implementation (lazy

#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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324934890&siteId=291194637