Ada and Queue
Ada the Ladybug has many things to do. She puts them into her queue. Anyway she is very indecisive, so sometime she uses the top, sometime the back and sometime she decides to reverses it.
Input
The first line consists of 1 ≤ Q ≤ 106, number of queries. Each of them contains one of following commands
back - Print number from back and then erase it
front - Print number from front and then erase it
reverse - Reverses all elements in queue
push_back N - Add element N to back
toFront N - Put element N to front
All numbers will be 0 ≤ N ≤ 100
Output
For each back/front query print appropriate number.
If you would get this type of query and the queue would be empty, print "No job for Ada?" instead.
Example Input
15 toFront 93 front back reverse back reverse toFront 80 push_back 53 push_back 50 front front reverse push_back 66 reverse front
Example Output
93 No job for Ada? No job for Ada? 80 53 66【分析】用deque模拟。
反转后,输入也要反转。
#include <iostream>
#include <cstdio>
#include <stack>
#include <cstring>
using namespace std;
const int maxn = 1e4 + 10;
typedef long long LL;
#define cl(a,b) memset(a,b,sizeof a);
int main()
{
int n;
while(~scanf("%d",&n)){
deque<int> q;
char s[100];
int x;
int flag=1;
while(n--){
scanf("%s",s);
if(s[0] == 'b'){
if(q.empty())
puts("No job for Ada?");
else{
if(flag){
printf("%d\n",q.back());
q.pop_back();
}
else{
printf("%d\n",q.front());
q.pop_front();
}
}
}
else
if(s[0] == 'f'){
if(q.empty())
puts("No job for Ada?");
else{
if(!flag){
printf("%d\n",q.back());
q.pop_back();
}
else{
printf("%d\n",q.front());
q.pop_front();
}
}
}
else
if(s[0] == 'r'){
flag = 1-flag;
}
else
if(s[0] == 'p'){
scanf("%d",&x);
if(flag)
q.push_back(x);
else
q.push_front(x);
}
else
if(s[0] == 't'){
scanf("%d",&x);
if(flag)
q.push_front(x);
else
q.push_back(x);
}
}
}
return 0;
}

本文介绍了一个关于Ada the Ladybug的编程挑战,她使用队列来管理任务,并且能够从队列的前后两端取出任务、反转队列以及将任务加入到队列的不同位置。文章通过一个具体的例子展示了如何使用双端队列(deque)来解决这个问题。
66

被折叠的 条评论
为什么被折叠?



