题解:UVA12207 That is Your Queue
板子题。
大意
有一个序列,里面包含从
N操作:将序列中的首项移动到最后。E x操作:将第x 项移动到最前。
现在有 N 操作,请输出处理的数。
解析
考虑使用 STL 中的双端队列。
前置知识
STL 中双端队列的定义方法与其它容器类似,为 deque<T> q(T 为数据类型,q 为容器名)。
还有几个常用函数:
front(): 返回队列首项。back(): 返回队列末项。push_front(x): 在队列的最前插入x .pop_front(): 弹出队列首项(无返回值)。push_back(x): 在队列的最后插入x .pop_back(): 弹出队列末项(无返回值)。erase(p): 删除队列的第p 项。
解题
对于 N 操作,我们只要存一下首项,然后弹出首项,再插入到最后就可以了。
对于 E 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;
}
但是,提交后,却迎来了这样的结果……
为什么?
观察数据范围,可得
所以:在给队列插入初始元素时,
代码
#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;
}
过了。