算法竞赛入门经典 习题5-7

该程序实现了一个不使用优先队列的打印任务调度模拟,通过维护额外的higher数组记录高优先级任务数量。对于输入的打印队列,它会重新排序并计算指定任务的打印时间。在循环中,如果队首任务有更高优先级的任务,则将其移到队尾,否则打印任务并更新higher数组。最后输出所需分钟数。

UVa12100

Printer Queue

打印队列中的任务存在优先级,如果队列中存在优先级更高的任务,则将队首任务放入队尾,在此种处理方式下,计算初始队列中指定位置任务的打印时间。

不能使用优先队列,因为这不是基于优先级的先来先服务调度机制。为了方便判断队列中是否存在优先级高的任务,使用额外的higher数组记录了高于当前优先级的任务的数量。

#include <iostream>
#include <deque>
#include <vector>

using namespace std;

int main()
{
	int T = 0;
	cin >> T;
	for (int t = 0; t < T; t++)
	{
		int n = 0, m = 0, priority;
		cin >> n >> m;
		deque<pair<int, bool>> queue;
		vector<int> higher(10, 0);
		for (int i = 0; i < n; i++)
		{
			cin >> priority;
			queue.push_back(pair<int, bool>(priority, i == m));
			for (int j = 1; j < priority; j++)
			{
				higher[j]++;
			}
		}
		int minute = 0;
		while (1) {
			if (higher[queue.front().first] > 0) {
				queue.push_back(queue.front());
				queue.pop_front();
			}
			else {
				minute++;
				if (queue.front().second) break;
				else {
					for (int j = 1; j < queue.front().first; j++)
					{
						higher[j]--;
					}
					queue.pop_front();
				}
			}
		}
		cout << minute << endl;
	}
	return 0;
}
/*
3
1 0
5
4 2
1 2 3 4
6 0
1 1 9 1 1 1
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值