题目地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1394
注意要点:
1根本不需要真正构建出树的结构 否则反而超内存
由于最后的结果等于 w【i】*l【i】求和
换成加法 w【i】应该加层数那么多次,而这样的构建方式使根结点的权值恰好等于所有叶子节点权值之和(包括中间状态)
所以在每次创建新结点时,把新结点的权值加到最后的结果中去,那么每个权值被加的次数等于它出于多少颗树中,恰好等于它的高度
2即使是weight 也应该用long long保存 因为p【i】已经可达10^9
#include<iostream>
#include<queue>
using namespace std;
typedef long long inta;
struct node
{
inta weight;
bool operator<(const node & a) const
{
return weight>a.weight;
}
};
int main()
{
int size;
cin>>size;
for(int l=0;l<size;l++)
{
priority_queue<node> pq;
int n;
cin>>n;
long long ans=0;
for(int i=0;i<n;i++)
{
int w;
cin>>w;
node temp;
temp.weight=w;
pq.push(temp);
}
while(pq.size()>1)
{
node n1=pq.top();
pq.pop();
node n2=pq.top();
pq.pop();
node newnode;
newnode.weight=n1.weight+n2.weight;
pq.push(newnode);
ans+=newnode.weight;
}
cout<<ans<<endl;
if(l<size-1) cout<<endl;
}
}