队列/优先队列(代码简单模式)

#include<stdio.h>
#include<queue>//头文件

using namespace std;

int main()
{
    queue<int>Q;//队列定义
    int n, i, t;
    while(scanf("%d", &n) != EOF)
    {
        for(i = 1 ; i <= n ; i++)
            Q.push(i);
        while(!Q.empty())//当队列不为空
        {
            t = Q.front();//返回队首元素
            Q.pop();//删除队首元素
            printf("%d ", t);
        }
        printf("\n");
    }
    return 0;
}//队列(先进先出)



优先队列

priority_queue<int> pq;
这样声明是默认为“ 越小整数的优先级越低的优先队列”
由于出队的元素不是最先入队的元素出队的方式要由 pq.front()变为 pq.top()

自定义类型的有限队列(结构体类型的优先队列)
struct node
{
    int  x,step;
    friend bool operator < (node n1, node n2)
    {
        return n1.step > n2.step;
    }
};



#include<stdio.h>
#include<queue>//头文件

using namespace std;

struct node
{
    int x, y;
    friend bool operator<(node a, node b)
    {
        return a.y > b.y;//从下到大
    }
};
int main()
{
    priority_queue<node>Q;//优先队列定义
    int n, i;
    node s, p;
    while(scanf("%d", &n) != EOF)
    {
        for(i = 1 ; i <= n ; i++)
        {
            scanf("%d%d", &s.x, &s.y);
            Q.push(s);
        }
        while(!Q.empty())//当队列不为空
        {
            p = Q.top();//返回队首元素
            Q.pop();//删除队首元素
            printf("%d %d\n", p.x, p.y);
        }
    }
    return 0;
}//优先队列

 

posted @ 2015-04-16 12:53  午夜阳光~  阅读(224)  评论(0编辑  收藏  举报