Uva12100 Printer Queue
题目
The only printer in the computer science students’ union is experiencing an extremely heavy workload. Sometimes there are a hundred jobs in the printer queue and you may have to wait for hours to get a single page of output. Because some jobs are more important than others, the Hacker General has invented and implemented a simple priority system for the print job queue. Now, each job is assigned a priority between 1 and 9 (with 9 being the highest priority, and 1 being the lowest), and the printer operates as follows.
• The first job J in queue is taken from the queue.
• If there is some job in the queue with a higher priority than job J, then move J to the end of the queue without printing it.
• Otherwise, print job J (and do not put it back in the queue).
In this way, all those important muffin recipes that the Hacker General is printing get printed very quickly. Of course, those annoying term papers that others are printing may have to wait for quite some time to get printed, but that’s life.
Your problem with the new policy is that it has become quite tricky to determine when your print job will actually be completed. You decide to write a program to figure this out. The program will be given the current queue (as a list of priorities) as well as the position of your job in the queue, and must then calculate how long it will take until your job is printed, assuming that no additional jobs will be added to the queue. To simplify matters, we assume that printing a job always takes exactly one minute, and that adding and removing jobs from the queue is instantaneous.
题意:
学生会里只有一台打印机,但是有很多文件需要打印,因此打印任务不可避免地需要等待。有些打印任务比较急,有些不那么急,所以每个任务都有一个1~9间的优先级,优先级越高表示任务越急。
打印机的运作方式如下:首先从打印任务里取出一个任务J,如果队列里有比J更急的任务,则直接把J放到打印队列的尾部,否则打印任务J(此时不会把它放回打印队列)。
输入打印队列里各个任务的优先级以及所关注任务在队列中的位置(队首位置为零),输出该任务完成的时刻。所有任务都需要1分钟打印。例如,打印队列{1,1,9,1,1,1},目前处于队首的任务完成时刻为5。
思路:记录所关注任务的值以及位置,模拟打印进程,每一次打印完后更新目标值的位置。以及队列长度(当目标值从队首回到队尾时,所处位置就是整个队列的长度)。
代码
#include<iostream>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 10010;
queue<int> q;
void clear(queue<int>& q){
queue<int> empty;
swap(empty, q);
}
int fun(queue<int>q){
int big = 0;
while(!q.empty()){
if(q.front() > big){
big = q.front();
}
q.pop();
}
return big;
}
int main(){
int t, n, m, x, len = 0, value;
cin>>t;
while(t--){
cin>>n>>m;
clear(q);
for(int i = 0; i < n; i++){
cin>>x;
if(i == m)
value = x;
q.push(x);
}
int cnt = 0;//记录时间
int len = n;
m++;
while(!q.empty()){
if(m == 1 && value == fun(q)){
cout<<++cnt<<endl;//输出目标值也要花时间
break;
}
else if(q.front() < fun(q)){//由于优先级小被重新放到队列尾,长度不变
q.push(q.front());
q.pop();
if(m == 1)
m = len;//队列里有优先级更大的,只能回到队尾
else
m--;
}
else{
q.pop();
cnt++;
len--;
m--;
}
}
}
return 0;
}
上一篇: UVa 712 - S-Trees
下一篇: JavaScript点击按钮开关灯案例