题解:UVA12207 That is Your Queue

· · 题解

板子题。

大意

有一个序列,里面包含从 1 到 P 的数。还有一下两种操作:

现在有 C 次操作,对于每个 N 操作,请输出处理的数。

解析

考虑使用 STL 中的双端队列。

前置知识

STL 中双端队列的定义方法与其它容器类似,为 deque<T> q(T 为数据类型,q 为容器名)。

还有几个常用函数:

解题

对于 N 操作,我们只要存一下首项,然后弹出首项,再插入到最后就可以了。

对于 E x 操作,我们只要遍历整个双端队列,找到 x 所在的位置后删除,最后把它插入到最前。

完整代码:

#include <bits/stdc++.h>
using namespace std;
int main() {
    int p, c, x, cnt = 0;
    char op;
    while ((cin >> p >> c) && (p != 0 && c != 0)) {
        deque<int> q;
        for (int i = 1; i <= p; i++)
            q.push_back(i);
        cout << "Case " << ++cnt << ":\n";
        while (c--) {
            cin >> op;
            if (op == 'N') {
                int f = q.front();
                cout << f << '\n';
                q.pop_front();
                q.push_back(f);
            } else {
                cin >> x;
                for (auto i = q.begin(); i != q.end(); i++)
                    if (*i == x) {
                        q.erase(i);
                        break;
                    }
                q.push_front(x);
            }
        }
    }
    return 0;
}

但是,提交后,却迎来了这样的结果……

为什么?

观察数据范围,可得 C < P. 所以,我们不可能把所有的病人全部处理一遍。

所以:在给队列插入初始元素时,i 应该最大到 \min(C, P).

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    int p, c, x, cnt = 0;
    char op;
    while ((cin >> p >> c) && (p != 0 && c != 0)) {
        deque<int> q;
        for (int i = 1; i <= min(c, p); i++)
            q.push_back(i);
        cout << "Case " << ++cnt << ":\n";
        while (c--) {
            cin >> op;
            if (op == 'N') {
                int f = q.front();
                cout << f << '\n';
                q.pop_front();
                q.push_back(f);
            } else {
                cin >> x;
                for (auto i = q.begin(); i != q.end(); i++)
                    if (*i == x) {
                        q.erase(i);
                        break;
                    }
                q.push_front(x);
            }
        }
    }
    return 0;
}

过了。