ACM训练——Mergeable Stack(链表模拟栈)

题目链接: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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值