首页 > 代码库 > 100197C

100197C

合并果子 每一次取最小的两个合并 答案加上这两个值 因为这是一颗二叉树,我们计算一条路的长度,可以看成从叶子节点逐渐合并,直到根

#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
typedef long long ll;
priority_queue<ll,vector<ll>,greater<ll> >q;
int n;
inline ll read()
{
    ll f=1,x=0;char c=getchar();
    while(c<0||c>9){if(c==-)f*=-1;c=getchar();}
    while(c>=0&&c<=9){x*=10;x+=c-0;c=getchar();}
    return x*f;
}
int main()
{
    freopen("huffman.in","r",stdin);
    freopen("huffman.out","w",stdout);
    n=read();
    for(int i=1;i<=n;i++){int l=read();q.push(l);}
    ll ans=0;
    while(q.size()>1)
    {
        ll a=q.top();q.pop();
        ll b=q.top();q.pop();
        ll x=a+b;
        ans+=x;q.push(x);
    }
    cout<<ans<<endl;
    fclose(stdin);
    fclose(stdout);
    return 0;
}

 

100197C