有n堆果子,每堆果子都有一个值,合并两堆果子需要和相加的体力,要求n堆果子和并成一堆果子最小花费的体力。
求n堆果子和并成一堆果子最小花费的体力。
利用堆的pop操作和top操作来解题。
#include <bits/stdc++.h>
using namespace std;
int n,s;
priority_queue<int,vector<int>,greater<int> >heap;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
int temp;
scanf("%d",&temp);
heap.push(temp);
}
int a,b;
while(heap.size()>=2)
{
a=heap.top();
heap.pop();
b=heap.top();
heap.pop();
s+=a+b;
heap.push(a+b);
}
printf("%d",s);
return 0;
}
浏览次数: