第一次见到这种写法所以补充一下
思路:
这道题一开始用的办法就是最傻的办法
1,2就不用说了吧,3的话就把数组整个换个顺序
#include#include using namespace std; int n; struct STACK { int top,data[1111111]={-1}; void init() { top=0; } int size() { return top; } void pop() { top--; } void push(const int &x) { top++; data[top]=x; } }st; int main() { int x,y; cin>>n; for(int i=1;i<=n;i++) { cin>>x; if(x==1) { cin>>y; st.push(y); cout< 看了看数据范围这是显然会超时的
然后了解还有种办法:可以搞个flag标记到底哪里是正着放还是反着放,数组只要稍微开大一点就行。
我写的代码:#include#include using namespace std; struct QUEUE { int head,tail,data[6666666]; void init() { head=300000; tail=300000; } int size() { return tail-head; } int front() { return data[head]; } int back() { return data[tail-1]; } void pop_back() { tail--; } void pop_front() { head++; } void push_back(const int &x) { data[tail]=x; tail++; } void push_front(const int &x) { head--; data[head]=x; } }qu; int main() { int q; cin>>q; int flag=0; qu.init(); for(int i=1;i<=q;i++) { int x; cin>>x; if(x==1) { int y; cin>>y; if(flag==0) qu.push_back(y); if(flag==1) qu.push_front(y); } if(x==2) { if(qu.size()==0) continue; if(flag==0) qu.pop_back(); if(flag==1) qu.pop_front(); } if(x==3) flag=flag^1; if(qu.size()==0) cout<<"-1"< 大佬的代码:
简洁版:#includeint a[666666],head,tail,q; bool status=0; int main() { head=tail=300010; tail--; scanf("%d",&q); for (int i=1;i<=q;i++) { int op;//option scanf("%d",&op); if (op==1) { int x; scanf("%d",&x); tail+=status^1; head-=status; a[status?head:tail]=x; } else if (op==2) { tail-=status^1; head+=status; } else status^=1; printf("%dn",head>tail?-1:a[status?head:tail]); } return 0; } 规范版:
#includestruct deque { int a[666666],head=300010,tail=300010-1; void push_back(const int &x) { a[++tail]=x; } void push_front(const int &x) { a[--head]=x; } void pop_back() { --tail; } void pop_front() { ++head; } int back() { return a[tail]; } int front() { return a[head]; } bool empty() { return head>tail; } }de; bool status=0; int q; int main() { scanf("%d",&q); for (int i=1;i<=q;i++) { int op;//option scanf("%d",&op); if (op==1) { int x; scanf("%d",&x); if (!status) de.push_back(x); else de.push_front(x); } else if (op==2) { if (!status) de.pop_back(); else de.pop_front(); } else status^=1; printf("%dn",de.empty()?-1:(status?de.front():de.back())); } return 0; } tips:
虽然是第一次见,但是还是渐渐对这个^(异或)有了一定的感觉
1^1=0;
1^0=1;
能够很巧妙的在1和0之间转换



