Description:
Alice准备在森林里面建一栋小木屋,现在他有一根长度为n的木块,需要把它们切割成m根长度分别为l1,l2,...,lm的更小的木块( sigma(li) = n )。而Alice每次只能将之前的某一块切成两块,每次切割木块会消耗Alice的体力,消耗的体力值为当前待切割的木块的长度。现在Alice请聪明的你帮忙,求Alice至少要消耗多少体力。
Input:
题目包含多组数据。第一行为一个整数m(1<=m<=100000),第二行为m个整数,分别表示m根长度分别为l1,l2,...,lm的更小的木块(1<=li<=65536)。
Output:
一个整数,表示Alice至少要消耗多少体力。
Sample Input:
3 8 5 8 4 2 3 4 4
Sample Output:
34 26
#include<cstdio> #include<queue> #include<algorithm> using namespace std; typedef long long LL; int main(){ int n,t; while(~scanf("%d",&n)){ priority_queue<int,vector<int>,greater<int> >work; // 两个>中间的空格不能省略
for(int i=0;i<n;i++){ scanf("%d",&t); work.push(t); } LL ans=0; while(work.size()>=2){ int min1=work.top();//这是第一小的 work.pop();//让第一小的离开队列 int min2=work.top();//这是第二小的 work.pop();//让第二小的离开队列 ans+=min1+min2;//这次合并用了这么多体力 work.push(min1+min2);//把最小的两个合并成新的,再加入进去 } printf("%lld ",ans); } return 0; }
队列:
#include<algorithm> using namespace std; int main(){ priority_queue<int>work; //work 变量名 work.push(124); //push 为加入到数列 work.push(13); work.push(1); printf("%d",work.top()); //返回最大 work.pop(); //读出队列中最大的数 return 0; }
綦文博 20:39:23 #include<cstdio> #include<queue> #include<algorithm> using namespace std; int main(){ priority_queue<int>work; work.push(124); work.push(13); work.push(13); work.push(6); work.push(1); work.push(345); work.push(9); work.push(3); work.push(12343); while(!work.empty()){ //work.empty用来判断是否队列是空的
printf("%d ",work.top());
work.pop();
} return 0; } //循环所有
work.size() 表示队列中还剩多少个
如果自动输入数据
scanf("%d",&n);
for(i=0;i<n;i++)
{scanf("%d",&t); work.push(t);} 优先队列出来的一定是最大的