Uva12100 Printer Queue 【queue+sort】【习题5-7】

来源:互联网 发布:云计算项目 编辑:程序博客网 时间:2024/06/06 05:43

 题目:Printer Queue

 题意:排队等待打印,优先级高的直接插队打印,队首的那个插入队尾继续等待,问第m位置的那个人打印需要多长时间?每个人打印需要1分钟;

 思路:(1)用结构体将每个人的位置和优先级存放,然后依次入队

           (2)将每个人的优先级按递减排序

           (3)遍历优先级数组,判断队首是否符合当前优先级,符合出队,不符合插入队尾,直到出现m位置的那个人时跳出即可!

代码:

#include <iostream>#include <queue>#include <map>#include <algorithm>using namespace std;struct node{    int position,grade;};queue<node>Q;bool cmp(int a,int b){    return a > b;}int main(){    int t,n,m,a[105];    cin >> t;    while(t--)    {        while(!Q.empty()) Q.pop();        cin >> n >> m;        node temp;        for(int i=0;i<n;i++)        {            cin >> a[i];            temp.position = i;            temp.grade = a[i];            Q.push(temp);        }        sort(a,a+n,cmp);        int cot = 0;        for(int i=0;i<n;i++)        {            cot++;            temp = Q.front();            while(temp.grade < a[i])//判断当前优先级            {                Q.pop();//出队                Q.push(temp);//插入队尾继续等待                temp = Q.front();            }            Q.pop();            if(temp.position == m)                break;        }        cout << cot <<endl;    }    return 0;}


0 0