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;}
新聞熱點
疑難解答