UVa10954 Add All (优先队列)

来源:互联网 发布:瑞安法院淘宝拍卖网 编辑:程序博客网 时间:2024/05/22 16:00

题目链接:https://vjudge.net/problem/UVA-10954

题目大意:有n个数的集合S,每次可以从S中删除两个数,然后把它们的和放回集合,直到剩下一个数。每次操作的开销等于剩下的两个数之和,求解最小的总开销。

题目思路:写一个堆动态维护一下,直接偷懒stl来一发优先队列。

代码:

#include <bits/stdc++.h>using namespace std;struct node{    int x;    bool operator<(const node&a)const{//确立优先级,队列中的最小的元素排在最前边        return a.x<x;    }};int main(){    priority_queue<node>Q;    int n;    node s;    while(~scanf("%d",&n)){        if(!n) break;        for(int i=0;i<n;i++){            scanf("%d",&s.x);            Q.push(s);        }        int ans=0;        while(Q.size()>1){            node tmp1=Q.top();Q.pop();            node tmp2=Q.top();Q.pop();            ans+=(tmp1.x+tmp2.x);            node tmp;            tmp.x=tmp1.x+tmp2.x;            Q.push(tmp);        }        //node tmp=Q.top();        Q.pop();        //ans+=tmp.x;        printf("%d\n",ans);    }}


原创粉丝点击