POJ 3253 Fence Repair

来源:互联网 发布:写真制作软件 编辑:程序博客网 时间:2024/06/16 07:39

贪心策略:每次取两根最短的棍子组合成根长的棍子,累加代价,组合出来的长棍子再加入到棍子的集合中,迭代直到只剩下一根棍子为止,用用优先队列维护中间数据效率会高一些。

#include <stdio.h>#include <queue>using namespace std;int arr[20005];typedef struct node{long long len;}node;bool operator < (const node &a, const node &b){return a.len > b.len;}void solve(int n){int i;long long cost;node node_ins;priority_queue<node> pq;for(i=0; i<n; i++){node_ins.len = arr[i];pq.push(node_ins);}cost = 0;while(1 != pq.size()){node_ins.len = 0;cost += pq.top().len;node_ins.len += pq.top().len;pq.pop();cost += pq.top().len;node_ins.len += pq.top().len;pq.pop();pq.push(node_ins);}printf("%lld\n", cost);}int main(void){int n, i;while(EOF != scanf("%d", &n)){for(i=0; i<n; i++)scanf("%d", arr+i);solve(n);}return 0;}


0 0
原创粉丝点击