POJ 2051 Argus STL 优先队列

来源:互联网 发布:巨人网络财报 编辑:程序博客网 时间:2024/05/21 08:36

POJ 2051

题意为:给出一系列值和其出现的时间周期,这些数值都将以其周期为规则不断地出现,问从零时刻开始前k个出现的数值,依次输出。若某时刻出现的数值不只一个,则按照从小到大的顺序输出。

显然这是优先队列的应用。

优先队列,priority_queue,可以直接借助STL实现,是一个在队列基础上给队列元素增加了优先级的数据结构,一般形式为:

priority_queue<type,container,fuction>q

其中type是定义队列元素的类型,可以是基础的int,double等,也可以是自定义的类型(struct)

container是容器,默认为vector;

function在此为比较函数,默认为operator< ,如果有需要可以重载运算符或者自己写一个新的判断方式;

在使用priotity_queue时,上面三个参数中必须指明元素类型,后两个参数缺省时保持默认的设定

这个题目的想法并不是很复杂,每次输出一个条目,就向队列中压入同样值的一个条目,其出现时间要比已经输出的条目多一个周期,为此定义结构体node,对每一个条目存储值,时间和周期。

code:

#include<iostream>#include<algorithm>#include<cstdio>#include<queue>#include<cstring>#include<vector>#include<cmath>#define maxn 100010using namespace std;struct node{    int value,time,period;};bool operator<(node a,node b){    if(a.time==b.time)        return a.value>b.value;    return a.time>b.time;}priority_queue<node>q;char op[20];int k;int main(){    while(cin>>op)    {        if(op[0]=='#')break;        node tmp;        scanf("%d%d",&tmp.value,&tmp.time);        tmp.period=tmp.time;        q.push(tmp);    }    scanf("%d",&k);    while(k--)    {        node tmp=q.top();        q.pop();        printf("%d\n",tmp.value);        node t=tmp;        t.time+=t.period;        q.push(t);    }}



0 0
原创粉丝点击