一.题目链接:
HDU-5929
二.题目大意:
有栈一枚,n 步 4 种操作.
PUSH x:将元素 x 压入栈中.( x 非 0 则 1)
POP:弹出栈顶首元素.
REVERSE:将栈逆序.
QUERY:定义一种操作 nand.
若栈为空则输出 "Invalid."
否则输出 nand nand .... nand
0 nand 0 = 1
0 nand 1 = 1
1 nand 0 = 1
1 nand 1 = 0
三.分析:
由于 n 太大,直接暴力会超时,只能用数组来模拟.
又观察到 0 nand (0 || 1)都等于 1,所以只需要用双端队列来存储 0 的位置.
最后判断就好.
四.代码实现:
#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-4
#define PI acos(-1.0)
#define ll long long int
using namespace std;
const int M = 200010;
int n;
int l;
int r;
int dir;
string s;
int a[M * 2];
deque <int> q;
int main()
{
int T;
scanf("%d", &T);
for(int c = 1; c <= T; ++c)
{
printf("Case #%d:\n", c);
l = M - 1;
r = M;
dir = 0;
q.clear();
scanf("%d", &n);
while(n--)
{
cin >> s;
if(s == "PUSH")
{
int data;
scanf("%d", &data);
if(dir)
{
a[r] = data;
if(!data)
q.push_back(r);
r++;
}
else
{
a[l] = data;
if(!data)
q.push_front(l);
l--;
}
}
else if(s == "POP")
{
if(dir)
{
r--;
if(!a[r])
q.pop_back();
}
else
{
l++;
if(!a[l])
q.pop_front();
}
}
else if(s == "REVERSE")
{
dir = !dir;
}
else if(s == "QUERY")
{
if(l + 1 == r)
printf("Invalid.\n");
else if(q.empty())
printf("%d\n", (r - l - 1) % 2);
else if(r - l == 2)
printf("%d\n", a[l + 1]);
else if(dir)
{
if(q.front() == r - 1)
{
int loc = r - l;
printf("%d\n", loc & 1);
}
else
{
int loc = q.front() - l;
printf("%d\n", loc & 1);
}
}
else
{
if(q.back() == l + 1)
{
int loc = r - l;
printf("%d\n", loc & 1);
}
else
{
int loc = r - q.back();
printf("%d\n", loc & 1);
}
}
}
}
}
return 0;
}