【C/C++】学生排队吃饭问题

问题:
有n个学生,学生们都在排队取餐,第个学生在L国时刻来到队尾,同一时刻来的学生编号小的在前,每个时刻当队列不为空时,排在队头的同学就可以拿到今天的中餐并离开队伍,若第个学生R团时刻不能拿到中餐,他就会离开队伍。问每个学生拿到中餐的的时刻(不能拿到的输出O)

输入描述:
第一行一个整数(1<t<100).接下来组数据,每组数据第一行一个整数n1<n≤10000)。接下来n行,每行两个整数L[i], R[i] (1 < L[i] < R[i] ≤5000).
输出描述:
每组测试数据输出一行,n个整数,每个学生拿到中餐的的时刻(不能拿到的输出0).

测试用例:

2
2
1 3
1 4
3
1 5
1 1
2 3

思路:
用time表示一个时间戳,每次服务的时候time++
读入一个学生,判断队列是否为空:
空:判断这个学生是否能服务
非空:学生入队尾;判断队头学生是否可以被服务(R[i]是否<=time)如果可以就服务,不可以就学生出队

代码:

#include <bits/stdc++.h>
using namespace std;

struct student
{
    int L;
    int R;
}; 

int main()
{
    queue <student> que;
    int t, n;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        int time = 1;
        for(int i = 1; i <= n; i++)
        {
            student tmp;
            scanf("%d %d", &tmp.L, &tmp.R);
            if(que.empty())
            {
                (tmp.R >= i)? cout << time++ : cout << 0;
                cout << " ";
            }
            else
            {
                que.push(tmp);
                tmp = que.front();
                while (tmp.R < time)
                {
                    que.pop();
                    tmp = que.front();
                }
                tmp = que.front();
                cout << time++ << " ";
                que.pop();
            }
        }
        cout << endl;
    }
}
原文地址:https://www.cnblogs.com/kinologic/p/14703446.html