poj3253 Fence Repair 贪心/优先队列

来源:互联网 发布:sop制作软件 编辑:程序博客网 时间:2024/06/05 01:52

题目大意:
给出n个木板长度,拼接两个木板需两个木板长度大小的开销,求拼接为一块木板的最小开销

大致思路:
每次选取两个最小的木板,然后拼接在一起,再放回,直至只剩最后一块木板

c++:

#include<cstdio>#include<queue>using namespace std;int main(){    int n;    while(scanf("%d",&n)!=EOF){        priority_queue<int,vector<int>,greater<int> > pque;        //运用优先队列,需要加上greater<int>使队头变为最小值        while(n--){            int x;            scanf("%d",&x);            pque.push(x);        }        long long sum=0;           //注意sum可能超出int范围        while(pque.size()>1){            int a=pque.top();            pque.pop();            int b=pque.top();            pque.pop();            sum+=a+b;            pque.push(a+b);        }        printf("%lld\n",sum);    }    return 0;}
0 0
原创粉丝点击