打印机
计算机科学学会中唯一的打印机正在经历非常繁重的工作。有时打印机队列中有一百个作业,您可能需要等待几个小时才能获得一页输出。
因为某些作业比其他作业更重要,所以Hacker已经为打印作业队列发明并实现了一个简单的优先级系统。现在,为每个作业分配1到9之间的优先级(其中9为最高优先级,1为最低),打印机的操作如下
- 将队列中的第一个作业J从队列中取出。
- 如果队列中的某些作业具有比作业J更高的优先级,则将J移动到队列的末尾而不打印它。
- 否则,打印作业J(并且不要将其放回队列中)。
这样,Hacker可以将自己特别喜欢的红烧肉食谱很快地打印出来。当然,其他人正在打印的那些令人讨厌的学期论文可能不得不等待相当长的时间才能得到打印,但这就是生活啊。
现在的问题在于,确定何时实际完成打印作业已经变得非常棘手。请您编写一个程序来解决这个问题。为了简化问题,我们假设打印作业始终只花费一分钟,并且从队列中添加和删除作业是即时的。
【输入形式】
带有正整数的一行:测试用例的数量(最多100个)。然后对于每个测试用例:
一行包含两个整数n和m,其中n是队列中的作业数(1≤n≤100),m是作业的位置(0≤m≤n -1)。队列中的第一个位置是数字0,第二个是数字1,依此类推。
一行,其中n个整数在1到9的范围内,给出了队列中作业的优先级。第一个整数赋予第一个作业的优先级,第二个整数赋予第二个作业的优先级,依此类推。
【输出形式】
对于每个测试用例,请用单个整数打印一行;假设没有其他打印作业到达,直到完成打印作业为止的分钟数。
【样例输入】
3
1 0
5
4 2
1 2 3 4
6 0
1 1 9 1 1 1
【样例输出】
1
2
5
#include<iostream>
using namespace std;
template <class T>
class seqQueue {
friend int main();
private:
T*elem;
int maxSize;
int front, rear;
void doubleSpace();
public:
seqQueue(int size = 10);
~seqQueue();
bool isEmpty()const;
void enQueue(const T&x);
T deQueue();
T getHead()const;
};
template<class T>
seqQueue<T>::seqQueue(int size)
{
elem = new T[size];
maxSize = size;
front = rear = 0;
}
template<class T>
seqQueue<T>::~seqQueue()
{
delete[]elem;
}
template<class T>
bool seqQueue<T>::isEmpty()const
{
return (front == rear);
}
template<class T>
T seqQueue<T>::deQueue()
{
front = (front + 1) % maxSize;
return elem[front];
}
template<class T>
T seqQueue<T>::getHead()const
{
return elem[(front + 1) % maxSize];
}
template<class T>
void seqQueue<T>::enQueue(const T&x)
{
if ((rear + 1) % maxSize == front)
{ doubleSpace(); }
rear = (rear + 1) % maxSize;
elem[rear] = x;
}
template<class T>
void seqQueue<T>::doubleSpace()
{
T*tmp = elem;
elem = new T[2 * maxSize];
for (int i = 1; i <= maxSize-1; i++)
{
elem[i] = tmp[(front + i) % maxSize];
}
front = 0;
rear = maxSize-1;
maxSize *= 2;
delete []tmp;
}
int main() {
int a,i,j,n,s,max,k;//max为现存最重要的等级数目
seqQueue<int>x,z;//x储存重要等级,z储存位置
cin >> a;//a为操作数,n为每组的打印总数(from 1),s为目标位置数(from 0)
for (i = 0; i <= a - 1; i++)
{
cin >> n>>s;
int y[100];
max = 0;
k = 1;//k为输出时间
for (j = 0; j <= n - 1; j++)
{
cin >> y[j];
if (y[j] > max) { max = y[j]; }
x.enQueue(y[j]);
z.enQueue(j);
}
while (1)
{
while (x.getHead() != max)
{
int tmp1 = x.deQueue();
int tmp2 = z.deQueue();
x.enQueue(tmp1);
z.enQueue(tmp2);
}
if (z.getHead() == s) { break; }
x.deQueue();
z.deQueue();
k++;
max = 0;
for (int m = (x.front + 1) % x.maxSize; m != (x.rear+1)%x.maxSize; m = (m + 1) % x.maxSize)
{
if (x.elem[m] > max)
max = x.elem[m];
}
}
cout << k<<endl;
x.front = x.rear = z.front = z.rear = 0;
}
system("pause");
}