方法一:Max刚刚开始开了1e6一直t,原来是memset初始化的时候超时,还是按题意来开数组比较好
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define INF 0x3f3f3f3f #define Max (int)3e5+10 int a[Max],top[Max],bottom[Max],next[Max]; int main() { int t,i,j; cin >> t; while (t--) { memset(a,0,sizeof a); memset(top,0,sizeof top); memset(bottom,0,sizeof bottom); memset(next,0,sizeof next); int n,q,op,s,v,t,cnt=0; scanf("%d%d",&n,&q); for(int i=0;i<q;i++) { scanf("%d",&op); if(op==1) { scanf("%d%d",&s,&v); a[++cnt]=v; if(!bottom[s]) bottom[s]=cnt; next[cnt]=top[s]; top[s]=cnt; } else if(op==2) { scanf("%d",&s); if(bottom[s]) { printf("%d\n",a[top[s]]); top[s]=next[top[s]]; if(top[s]==0) bottom[s]=0; } else printf("EMPTY\n"); } else { scanf("%d%d",&s,&t); if(top[t]!=0) { if(top[s]==0) bottom[s]=bottom[t]; next[bottom[t]]=top[s]; top[s]=top[t]; } bottom[t]=top[t]=0; } } } return 0; }
方法二:自己手写一个栈
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define INF 0x3f3f3f3f #define Max int(1e5+10) class node { public: node *next,*pre; ll value; node() { pre=NULL; next=NULL; } node(int v,node *node_next=NULL,node *node_pre=NULL): value(v),next(node_next),pre(node_pre){ } }; class Stack { public: node *tail,*head; Stack(){ tail=NULL; head=NULL; } void push(ll v) { if(tail==NULL) { head=new node(v,NULL,NULL); tail=head; } else { tail->next=new node(v,NULL,tail); tail=tail->next; } } int pop() { ll t; if(tail!=NULL) { t=tail->value;//勿忘记只有一个元素的情况 if(tail==head) { tail=NULL; head=NULL; return t; } node *tt=tail; tail=tail->pre; tail->next=NULL; delete tt; } return t; } void ppop() { if(tail==NULL) printf("EMPTY\n"); else printf("%lld\n",pop()); } void connect(Stack &t)//此处一定要加上&,不然不会对原栈起到修改作用 { if(t.tail==NULL) return; if(this->tail==NULL) { this->tail=t.tail; this->head=t.head; t.tail=NULL; t.head=NULL; return; } this->tail->next=t.head;//勿忘记将两个栈先连接起来 t.head->pre=this->tail;//next pre都要考虑 this->tail=t.tail; t.tail=NULL; t.head=NULL; } }; int main(){ int t; scanf("%d",&t); while(t--) { int n,p; scanf("%d%d",&n,&p); Stack s[n+1]; while(p--) { int op; scanf("%d",&op); if(op==1) { int ss,v; scanf("%d%d",&ss,&v); s[ss].push(v); } if(op==2) { int ss; scanf("%d",&ss); s[ss].ppop(); } if(op==3) { int ss,t; scanf("%d%d",&ss,&t); s[ss].connect(s[t]); } } } return 0; }