`
haierboos
  • 浏览: 439539 次
文章分类
社区版块
存档分类
最新评论

【数据结构】队列

 
阅读更多

1.介绍


与栈一样,队列(queue)也是一种基本的数据结构,也有两种的基本操作:push和pop;与栈不一样的是,操作限制在队列的两端。push是从队尾(rear)插入元素,即入列;pop是从队首删除元素,即出列。在出列过程中,要判断队列是否为空


队列可以用数组进行模拟,也可以用链表作为存储。


2.问题


2.1 POJ 3125


题目是关于优先级调度,每个job有一个0~9的优先级,优先级高的先打印,同等优先级的在排在队列前面的先打印。


思路:用prio_count[ i ]记录优先级为i的job个数,i的初始值置为9,每一次循环后减1;若i减至priority[m],且队首元素为m,整个循环结束;否则,进入下面的步骤;

通过判断队首优先级==i,若相等,则出列;若不等,则将队首元素插入队尾。


一次提交AC,幸之。


源代码:

3125 Accepted 128K 0MS C++ 906B 2013-08-29 15:08:43
#include <iostream>
#include <queue>
using namespace std;

#define MAX 100

int main()
{
	/*pop_count represents the count of dequeue
	  prio_count represents the count of priority 0 ~ 9*/
	int testcases,n,m,i,pop_count;      
	int priority[MAX],prio_count[10];   
	queue<int>que;
	scanf("%d",&testcases);
	while(testcases--)
	{
		scanf("%d%d",&n,&m);

		/*initialization and clear the queue*/
		pop_count=0;
		memset(prio_count,0,sizeof(prio_count));		
		while(!que.empty())
			que.pop();
		
		/*push jobs to the queue, get the count of priority 0 ~ 9*/
        for(i=0;i<n;i++)
		{
			scanf("%d",&priority[i]);
			prio_count[priority[i]]++;
			que.push(i);
		}
		
		for(i=9;i>=priority[m];i--)
		{
			while(prio_count[i])
			{
				/*indicate that your job gets its turn to print*/
				if(i==priority[m]&&que.front()==m)
				{
					pop_count++;
					break;
				}
				else
				{
					if(priority[que.front()]==i)
					{
						que.pop();
						pop_count++;
						prio_count[i]--;
					}
					else
					{
						que.push(que.front());
						que.pop();
					}
				}
			}
		}
		printf("%d\n",pop_count);
	}
	return 0;
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics