标签:数据结构
STL实现优先队列使用方法:
头文件:
声明方式:
结构体的声明方式:
<span style="font-size:12px;">struct node
{
      int x, y;
       friend bool operator < (node a, node b)
      {
             return a.x > b.x; //结构体中,x小的优先级高
      }
};
</span>
priority_queue<node>q;//定义方法
//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
基本操作:
empty() 如果队列为空返回真
pop() 删除对顶元素
push() 加入一个元素
size() 返回优先队列中拥有的元素个数
top() 返回优先队列对顶元素
在默认的优先队列中,优先级高的先出队。
在本题中,因要求“如果遇到两个优先权一样的病人的话,则选择最早来的病人“,所以在判断优先级时,除了看优先权值外,还需要看病人的编号(id),
代码如下:
struct hos
{
	int ran,id;
	friend bool operator <(hos a,hos b)
	{
		if(a.ran==b.ran)
			return a.id>b.id;
			return a.ran<b.ran;
	}
}
没什么好说的,完全模板题,该题的全代码如下:
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;		//这句话很牛逼啊,少了不行啊
struct hos
{
	int ran,id;
	friend bool operator <(hos a,hos b)
	{
		if(a.ran==b.ran)
			return a.id>b.id;
			return a.ran<b.ran;
	}
}t;
int main()
{
	int n,k,a,b;
	char s[5];
	while(scanf("%d",&n)!=EOF)
	{
		k=1;
		priority_queue<hos>q[4];
		while(n--)
		{
			scanf("%s",s);
			if(s[0]=='I')
			{
				scanf("%d%d",&a,&b);
				t.id=k++;
				t.ran=b;
				q[a].push(t);
			}
			else
			{
				scanf("%d",&a);
				if(!q[a].empty())
				{
					printf("%d\n",q[a].top().id);
					q[a].pop();
				}
				else
					printf("EMPTY\n");
			}
		}
	}
	return 0;
}
 
标签:数据结构
原文地址:http://blog.csdn.net/u013068502/article/details/38332911