阅读: 28 评论: 0 作者: over 发表于 2009-10-17 12:43 原文链接
这道题的大意是有一个农夫要把一个木板砍成几块给定长度的小木板,每次据都要收取一定费用,这个费用就是据的这个木版的长度,用赫夫曼树的思路,用优先队列实现。逆向思维,每次都把木板拼接,要想每次都花费最少就得取最小的两个木板拼接起来再把拼接好的木板入队。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
1 #line 5"3243.cpp"
2 #include <iostream>
3 #include <vector>
4 #include <queue>
5 using namespace std;
6 struct cmp{
7 bool operator()(const int &i, const int &j){
8 return i>j;
9 }
10 };
11 int main()
12 {
13 int n,i,a,b,temp;
14 priority_queue <int, vector<int>,cmp>q;
15 __int64 sum;
16 while(cin>>n)
17 {
18 sum = 0;
19 for(i=0; i<n; i++)
20 {
21 cin>>temp;
22 q.push(temp);
23 }
24 while(q.size() != 1)
25 {
26 a = q.top();
27 q.pop();
28 b= q.top();
29 q.pop();
30 sum += (a + b);
31 q.push(a + b);
32 }
33 cout<<sum<<endl;
34 }
35 return 0;
36 }
37 ![](https://www.cnblogs.com/terminatro/aggbug/1585026.html?type=1)
发表评论
新闻频道:微软:Windows Mobile将整合Xbox Live
推荐链接:Windows 7专题发布
网站导航:博客园首页 个人主页 新闻 社区 博问 闪存 知识库