poj 3253 Fence Repair(优先队列)

来源:互联网 发布:渡边直美 知乎 编辑:程序博客网 时间:2024/06/08 08:26

题目链接

http://poj.org/problem?id=3253

Fence Repair
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 32617 Accepted: 10508

Description

Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the "kerf", the extra length lost to sawdust when a sawcut is made; you should ignore it, too.

FJ sadly realizes that he doesn't own a saw with which to cut the wood, so he mosies over to Farmer Don's Farm with this long board and politely asks if he may borrow a saw.

Farmer Don, a closet capitalist, doesn't lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.

Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.

Input

Line 1: One integer N, the number of planks 
Lines 2..N+1: Each line contains a single integer describing the length of a needed plank

Output

Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts

Sample Input

3858

Sample Output

34
题目大意:

现在要将一块很长的模板切割成N块。每次切断模板时,需要的开销为这块模板的长度。求最小的开销。例如15的木板切割成1,2,3,4,5的木块。最小的开销方法是先切成6和9,这样开销为15。再把9切成4和5。这样开销为24。再把6切成3和3.这样开销为30.。最后把3切成1和2.最小的开销是33.

思路:

用优先队列,思路是把一块块木板上的最小开销,每次拼完木板,把开销排序。

代码

#include<iostream>#include<algorithm>#include<cstring>#include<cstdio>#include<queue>using namespace std;struct T{    int x;    bool operator<(const T&a) const{        return a.x<x;    }};T a[20019];int main(){    int n;    long long res;    priority_queue<T> q;    while(~scanf("%d",&n)){        res=0;        for(int i=0;i<n;i++){            scanf("%d",&a[i].x);            q.push(a[i]);        }        for(int i=0;i<n-1;i++){            T temp;            T x=q.top();q.pop();            T y=q.top();q.pop();            res+=x.x+y.x;            temp.x=x.x+y.x;            q.push(temp);        }        while(!q.empty()) q.pop();        cout<<res<<endl;    }    return 0;}




0 0
原创粉丝点击