度度熊学队列

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6375

虽然数据结构里有双端队列,但是直接使用会造成内存溢出,在这里,使用list来模拟队列即可

代码如下:

#include <cstdio>
#include <list>
using namespace std;
const int maxn = 150000+20;
list<int> lists[maxn];


void read(int &x)
{
    char ch = getchar();
    x = 0;
    for (; ch < '0' || ch > '9'; ch = getchar());
    for (; ch >='0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
}

void init(int n)
{
    for(int i=1; i<=n; i++)
        lists[i].clear();
}

int main()
{
    int n,q;
    while(~scanf("%d%d",&n,&q))
    {
        init(n);
        while(q--)
        {
            int a,b,c,d;
            read(a);
            read(b);
            read(c);
            if(a==1)
            {
                read(d);
                if(c==0)
                {
                    lists[b].push_front(d);
                }
                else
                {
                    lists[b].push_back(d);
                }
            }
            else if(a==2)
            {


                if(lists[b].empty())   ///size T了
                {
                    puts("-1");
                }
                else
                {
                    if(c==0)
                    {
                        printf("%d\n",lists[b].front());
                        lists[b].pop_front();
                    }
                    else
                    {
                        printf("%d\n",lists[b].back());
                        lists[b].pop_back();
                    }
                }

            }
            else
            {
                read(d);
                if(d==0)
                {
                    lists[b].splice(lists[b].end(), lists[c]);
                }
                else
                {
                    lists[c].reverse();
                    lists[b].splice(lists[b].end(), lists[c]);
                }

            }
        }
    }
    return 0;
}

 

posted @ 2018-08-13 00:01  琥琥笙威  阅读(135)  评论(0编辑  收藏  举报