C Mergeable Stack(list超好用)

ZOJ  4016

list用法https://www.cnblogs.com/LLLAIH/p/10673068.html

一开始用普通的栈做,超内存,链表模拟栈也没写出来orz.
补题发现list超好用,真的-6-

有三个操作:1/向栈里添加数

                      2/输出栈顶元素然后pop掉

                      3/将栈b合并到栈a里并将栈b清空(注意合并后的顺序)

注意注意注意!!一定要将需要使用的list元素进行清空否则会WA!!

注意合并两个list序列时,用merge的话,会将合并后的序列进行默认的升序排列,所以这题要用splice

#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <list>
#include <map>
#include<stack>
#include<vector>
#define eps 1e-6
#define mod 1000000000
#define PI acos(-1)
#define inf 0x3f3f3f3f
#define MAX 3e5+5
#define read(x) scanf("%d",&x)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn=300005;
typedef long long LL;
list<int> a[maxn];
int main(){
    int t,n,q,s,v;
    scanf("%d",&t);
    while(t--){
        int op;
        list<int>::iterator it;
        scanf("%d%d",&n,&q);
        for(int i=1;i<=n;i++)
            a[i].clear();//清空list里每个元素
        for(int i=1;i<=q;i++){
            scanf("%d",&op);
            if(op == 1){
                scanf("%d%d",&s,&v);
                a[s].push_back(v);//将元素从尾部插入
            }
            else if(op == 2){
                scanf("%d",&s);
                if(a[s].empty())//判断该栈是否为空
                {
                    printf("EMPTY
");
                    continue;
                }
                printf("%d
",a[s].back());//输出栈顶元素即尾部第一个元素
                a[s].pop_back();//将栈顶元素弹出
            }
            else {
                scanf("%d%d",&s,&v);
                a[s].splice(a[s].end(),a[v]);//将栈v合并到栈s,并清空栈v
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/LLLAIH/p/10672988.html