题意:
将一根的木棍,看成符合要求的木棍。每次砍木棍的开销是被砍木棍的长度。求最小代价。
思路:
如果正向思考,那么就是将一根木棍砍成若干根木棍,这个过程可以形成无数种可能,复杂度高。我们不妨逆向思考,已经知道目标和原始状态,由于从原始状态到目标,可能性太多了。不妨从复杂的状态到原始状态,由多归一。
这道题提醒了我们逆向思维的重要性。
具体看代码注释。
AC code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn = 2e4 + 100;
int n,wood[maxn];
void solve(){
//声明一个从小到大取出数值的优先队列
priority_queue<int,vector<int>,greater<int> >que;
LL ans = 0;
for(int i = 1;i <= n;++i){
que.push(wood[i]);
}
while(que.size() > 1){//循环到只剩一块木板为止
//取出最短和次短的木块
int a1 = que.top();
que.pop();
int a2 = que.top();
que.pop();
//把两块木块合并
ans += a1 + a2;
que.push(a1 + a2);
}
printf("%I64d\n",ans);
}
int main(){
while(scanf("%d",&n) != EOF){
for(int i = 1;i <= n;++i){
scanf("%d",&wood[i]);
}
solve();
}
return 0;
}