码迷,mamicode.com
首页 > 其他好文 > 详细

优先队列

时间:2017-03-29 15:59:46      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:str   插入   while   function   nbsp   int   const   操作   运算   

优先队列:顾名思义,首先它是一个队列,但是它强调了“优先”二字,所以,已经不能算是一般意义上的队列了,它的“优先”意指取队首元素时,有一定的选择性,即根据元素的属性选择某一项值最优的出队~
百度百科上这样描述的:
  优先级队列 是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权的元素
  优先队列的类定义  
  优先队列是0个或多个元素的集合,每个元素都有一个优先权或值,对优先队列执行的操作有1) 查找;2) 插入一个新元素;3) 删除.在最小优先队列(min priorityq u e u e)中,查找操作用来搜索优先权最小的元素,删除操作用来删除该元素;对于最大优先队列(max priority queue),查找操作用来搜索优先权最大的元素,删除操作用来删除该元素.优先权队列中的元素可以有相同的优先权,查找与删除操作可根据任意优先权进行. 
优先队列,其构造及具体实现我们可以先不用深究,我们现在只需要了解其特性,及在做题中的用法,相信,看过之后你会收获不少。
使用优先队列,首先要包函STL头文件"queue",
以一个例子来解释吧(呃,写完才发现,这个代码包函了几乎所有我们要用到的用法,仔细看看吧):

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include<functional>
#define MAXSIZE 1000005
using namespace std;

//定义结构,使用运算符重载,自定义优先级1
struct cmp1
{
bool operator()(int &a,int &b)
{
return a>b;//最小值优先
}
};

struct cmp2
{
bool operator()(int &a,int &b)
{
return a<b;//最大值优先
}
};

//定义结构,使用运算符重载,自定义优先级2
struct node1
{
int x;
bool operator < (const node1 &a) const
{
return x>a.x; //最小优先级
}

};

struct node2
{
int x;
bool operator < (const node2 &a) const
{
return x < a.x; //最大优先级
}
};

int a[15]= {8,7,9,6,2,1,3,4,0,5};
node1 b[15]= {8,7,9,6,2,1,3,4,0,5};
node2 c[15]= {8,7,9,6,2,1,3,4,0,5};

int main()
{
priority_queue<int>q1; //默认优先级(最大优先级)
priority_queue<int,vector<int>,cmp1>q2; //最小优先级
priority_queue<int,vector<int>,cmp2>q3; //最大优先级
priority_queue<int,vector<int>,greater<int> >q4; //最小优先级
priority_queue<int,vector<int>,less<int> >q5; //最大优先级
priority_queue<node1>q6;
priority_queue<node2>q7;

for(int i=0; i<10; i++)
{
q1.push(a[i]);
q2.push(a[i]);
q3.push(a[i]);
q4.push(a[i]);
q5.push(a[i]);
}
for(int i=0; i<10; i++)
q6.push(b[i]);

for(int i=0; i<10;i++)
q7.push(c[i]);

while(!q1.empty())
{
printf("%3d",q1.top());
q1.pop();
}
printf("\n");

while(!q2.empty())
{
printf("%3d",q2.top());
q2.pop();
}
printf("\n");

while(!q3.empty())
{
printf("%3d",q3.top());
q3.pop();
}
printf("\n");

while(!q4.empty())
{
printf("%3d",q4.top());
q4.pop();
}
printf("\n");

while(!q5.empty())
{
printf("%3d",q5.top());
q5.pop();
}
printf("\n");

while(!q6.empty())
{
printf("%3d",q6.top());
q6.pop();
}
printf("\n");

while(!q7.empty())
{
printf("%3d",q7.top());
q7.pop();
}
printf("\n");

return 0;
}

 

输出如下:

9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0

 

优先队列

标签:str   插入   while   function   nbsp   int   const   操作   运算   

原文地址:http://www.cnblogs.com/alan-W/p/6639825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!