Fence Repair (PKU 3253)

Rence Repair

题目:
农夫约翰为了修理栅栏,要将一块很长的木板分割成N块。准备切成的木板的长度为L1、L2、……、Ln. 未切割木板的长度恰好为切割木板的长度和。每次切断木板时,需要的开销为这块木板的长度。例如,长度为21的木板切割成5、8、8的三块木板。长为21的木板切割成13、8时,开销为21.再将长度为13的木板切割成长度5、8时,开销为13.于是合计开销为34。于是按题目要求将木板切割完,最小的开销是多少?

限制条件:
1<=N<=2000
0<=Li<=5000

输入样例:
N=3, L={8, 5, 8}
输出样例:
34

Rence Repair问题在前面已经学习了使用贪心算法并构造哈弗曼数来解决此问题:

https://blog.csdn.net/qq_28120673/article/details/81028306

现在我们可以使用优先队列来完成此题目:
该问题主要算法是:

  1. 每次从所有的木板中取出最小的木板,长度相加的L
  2. 记录ans+=L;
  3. 判断优先级队列是否为空,如果为不为空就空则转步骤一;如果为空则输出ans.

    代码如下:

#include <iostream>
#include <queue>

#define MAX_N  1000

using namespace std;


int  N,L[MAX_N];
priority_queue<int, vector<int>, greater<int>> que;  //从小到大取出数据的优先级队列

void init(){
    cin>>N;
    for(int i=0;i<N;i++){
        cin>>L[i];
    }

}

int solve(){
    for(int i=0;i<N;i++){
        que.push(L[i]);
    }
    int ans=0;
    while(!que.empty()){
        int a=que.top();
        que.pop();
        int b=que.top();
        que.pop();
        int t=a+b;
        ans+=t;
        if(!que.empty()) que.push(t);
    }
    return ans;
}


int main(){
    init();
    cout<<solve();
}

关于priority_queue是知识

priority_queue优先级队列,其底层是采用堆来实现的。
它有两种构造方法:
1、priority_queue<int> q
该构造,默认为构造大根堆,即队首取出的是最大值
2、 priority_queue<int, vector<int>, less<int> >
该构造方法中的第三个参数表示构造大根堆还是小根堆。less<int> 表示构造大根堆,greater<int>表示数字小的优先级大。 priority_queue<int,vector<int>,greater<int> >;表示数字小的优先级大。在上面的例子中,我们在priority_queue中加入的是int数据,可以直接比大小。如果我们使用类作为队列的数据,那么队列怎么比较大小呢?我们有两种方法实现类的排序:
方法一:重载运算符 ‘<’
例如声明类People:

class Peolpe{
    private:
        int age;
        bool sex;
        //...
    private:
         // "<" 表示 price 大的优先级高
        friend bool operator<(const People & p) const {
            return(this.age<p.age);
        } 
}
//调用构造方法:
priority_queue<People> que;

方法二:在类的外部定义重载

struct cmp{
     // "<" 表示 price 大的优先级高
        bool operator() (People p1,people p2){
            return p1.age < p2.age;
}

//调用构造方法:
priority_queue<People, vector<People>,cmp > que;

参考priority_queue:

https://blog.csdn.net/pzhu_cg_csdn/article/details/79166858

猜你喜欢

转载自blog.csdn.net/qq_28120673/article/details/81093231