题目链接:https://zoj.pintia.cn/problem-sets/91827364500/problems/91827370237
此题直接模拟要么超时要么超内存,有些博客用到 list容器,这是双向链表实现的容器。以下给出了用双向链表模拟栈的解法。。。。。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <cstdio>
#include <string>
#include <stack>
#include <set>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
typedef int ll;
//双向链表节点
struct node{
int num;
node *next_s;
node *pre;
};
node * l[300010];//l[i],第i个栈的bottom
node * r[300010];//r[i],第i个栈的top
int siz[300010];//siz[i]第i个栈的大小
int main()
{
IOS;
ll t,n,q,flag,x,y;
cin>>t;
while(t--){
memset(siz,0,sizeof(siz));
cin>>n>>q;
//初始化栈
for(int i=1;i<=n;i++){
l[i]=NULL;
r[i]=NULL;
}
while(q--){
cin>>flag;
if(flag==1){
cin>>x>>y;
//入栈
node *p=new node;
p->num=y;
p->next_s=NULL;
p->pre=r[x];
if(r[x]==NULL){
r[x]=p;
}
else r[x]->next_s=p;
r[x]=p;
siz[x]++;
if(siz[x]==1){
l[x]=p;
}
}
else if(flag==2){
cin>>x;
//出栈
if(siz[x]){
cout<<r[x]->num<<endl;
r[x]=r[x]->pre;
if(r[x]) {//如果siz[x]==1,r[x]=NULL,就不存在r[x]->next_s;
delete r[x]->next_s;
r[x]->next_s=NULL;
}
else l[x]=r[x];
siz[x]--;
}
else cout<<"EMPTY"<<endl;
}
else {
cin>>x>>y;
//move stack
if(r[x]) r[x]->next_s=l[y];
else l[x]=l[y];
node *p=l[y];
if(p) { p->pre=r[x]; r[x]=r[y];}
siz[x]+=siz[y];
siz[y]=0;
l[y]=NULL;
r[y]=NULL;
}
}
}
getchar();
getchar();
return 0;
}