100197C

时间:2021-01-11 17:31:10

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

#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=,x=;char c=getchar();
while(c<''||c>''){if(c=='-')f*=-;c=getchar();}
while(c>=''&&c<=''){x*=;x+=c-'';c=getchar();}
return x*f;
}
int main()
{
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
n=read();
for(int i=;i<=n;i++){int l=read();q.push(l);}
ll ans=;
while(q.size()>)
{
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 ;
}

相关文章