根据nand的运算法则,发现 任何 nand 0 都等于1,题目是要从top nand 到 bottom,所以如果没有reverse的话就是要记录第一个出现的0的位置,然后看在这个0之前有多少个1,就可以直接推出答案;假设在查询之前reverse一下了,就是记录最后一个0出现的位置,然后看在这个0之后还有多少个1。
所以可以设一个类似双端队列的东西,直接开40W的数组,设两个指针,head、tail。根据是否reverse从head nand到 tail,或者从 tail nand 到head 。
【代码】
/* ***********************************************
Author :angon
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define showtime fprintf(stderr,"time = %.15f\n",clock() / (double)CLOCKS_PER_SEC)
#define lld %I64d
#define REP(i,k,n) for(int i=k;i<n;i++)
#define REPP(i,k,n) for(int i=k;i<=n;i++)
#define scan(d) scanf("%d",&d)
#define scanl(d) scanf("%I64d",&d)
#define scann(n,m) scanf("%d%d",&n,&m)
#define scannl(n,m) scanf("%I64d%I64d",&n,&m)
#define mst(a,k) memset(a,k,sizeof(a))
#define LL long long
#define N 1005
#define mod 1000000007
inline int read(){int s=0;char ch=getchar();for(; ch<'0'||ch>'9'; ch=getchar());for(; ch>='0'&&ch<='9'; ch=getchar())s=s*10+ch-'0';return s;}
int st[400006];
char op[10];
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int t,cs=1,x;
scan(t);
while(t--)
{
int n; scan(n);
int l = 200001, r=200000; //l设为r+1,则st[l]即为第一个出现的0的位置
int dir = 1;
int head = 0,tail = 1; //head,tail表示队列的两端
printf("Case #%d:\n",cs++);
while(n--)
{
scanf("%s",op);
if(op[2]=='S')
{
scan(x);
if(dir)
{
head++;
if(!x) st[++r] = head; //记录各个0出现的位置
}
else
{
tail--;
if(!x) st[--l] = tail;
}
}
else if(op[2]=='P')
{
if(dir)
{
head--;
if(st[r]>head) r--;
}
else
{
tail++;
if(st[l]<tail) l--;
}
}
else if(op[2]=='V')
{
dir ^= 1; //逆转只需要改变nand开始的方向
}
else
{
if(head<tail) puts("Invalid."); //初始即tail-head=1的
else if (l>r) printf("%d\n",(head-tail+1)&1); //全是1的情况
else
{
if(dir)
{
int tmp = st[l] - tail; //0之后的1的个数
if(st[l]==head) tmp++; //如果0之前没有东西,那之前的答案是0
printf("%d\n", !(tmp&1));
}
else
{
int tmp = head - st[r];
if(tail==st[r]) tmp++; //如果0之前没有东西,那之前的答案是0
printf("%d\n",!(tmp&1));
}
}
}
}
}
return 0;
}