28PUSH 1QUERYPUSH 0REVERSEQUERYPOPPOPQUERY3PUSH 0REVERSEQUERY Sample OutputCase #1:11Invalid.Case #2:0HintIn the first sample: during the first query, the stack contains only one element 1, so the answer is 1. then in the second query, the stack contains 0, l(from bottom to top), so the answer to the second is also 1. In the third query, there is no element in the stack, so you should output Invalid. 题意:Mr.frog最近在学习栈。栈有一些基础的操作:
PUSH x:将x放入栈中,x必须是0或1
POP:将栈顶元素取出
这些都太简单,Mr.Frog又增加了两个操作:
REVERSE:将栈中的元素翻转
QUERY:从左到右对栈中元素做NAND运算,输出运算结果,栈空输出“Invalid”。
另外,NAND是基于二进制的操作:
0 nand 0 = 1
0 nand 1 = 1
1 nand 0 = 1
1 nand 1 = 0 思路:用模拟栈+deque(双端队列)来解决。
用普通方法做,果断T了,现学了一下deque的用法,附学习的网址:
deque的使用
#include <iostream>#include <algorithm>#include <deque>#include <cstdio>#include <string>#include <cstring>using namespace std;deque<int > q;//存放data[]中0的位置int data[450000];//模拟栈int T;//测试数据int n;//操作数int Case;int t, h;//data[]的下标int main(){ scanf("%d",&T); Case = 1; while(T--) { q.clear(); t = 200000; h = 200001; bool flag = false;//false则不需翻转;true则需要翻转 int index = 0;//模拟栈中元素的个数 scanf("%d",&n); printf("Case #%d:/n",Case); Case++; while(n--) { char str[8]; scanf("%s",str); if(str[2] == 'S')//PUSH { int value; scanf("%d",&value); if(flag)//REVERSE { data[t--] = value; if(!value) q.push_front(t + 1); } else { data[h++] = value; if(!value) q.push_back(h - 1); } index++; } else if(str[2] == 'P')//POP { index--; if(flag) { if(data[++t] == 0) q.pop_front(); } else { if(data[--h] == 0) q.pop_back(); } } else if(str[2] == 'V')//REVERSE flag = !flag; else { if(index == 0) printf("Invalid./n"); else if(index == 1) printf("%d/n",data[h - 1]); else { int num = 0; if(q.empty()) num = index; else { if(flag) num = (q.back() == t+1) ? index - 1 : h - q.back(); else num = (q.front() == h-1) ? index - 1 : q.front() - t; } if(num % 2) printf("1/n"); else printf("0/n"); } } } } return 0;}
新闻热点
疑难解答