跳到正文

休闲·娱乐

用O(1)个栈实现一个队列,所有操作最坏O(1)

HPJG约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年5月12日
收录
2026年9月5日
更新
2026年11月10日
篇幅
约 5 分钟

版本

  1. v1当前
C++
#include <iostream>
#include <vector>
#include <stack>

using namespace std;

struct Queue
{
    stack<int,vector<int>> a, b, c, aa, bb, cc, d, e, ee, rm, t, tt;
    bool rotate()
    {
        if (!t.empty())
            t.pop();
        if (!tt.empty())
            tt.pop();
        if (!bb.empty())
        {
            e.push(bb.top());
            ee.push(bb.top());
            bb.pop();
            return 0;
        }
        if (!aa.empty())
        {
            d.push(aa.top());
            aa.pop();
            return 0;
        }
        if (!d.empty())
        {
            e.push(d.top());
            ee.push(d.top());
            d.pop();
            return 0;
        }
        if (!rm.empty())
        {
            rm.pop();
            e.pop();
            ee.pop();
            return 0;
        }
        return 1;
    }
    void update()
    {
        bool res = 0;
        for (int i = 0; i < 6; ++i)
            res = rotate();
        if (res)
        {
            swap(a, t);
            swap(b, tt);
            swap(a, e);
            swap(aa, ee);
            swap(b, c);
            swap(bb, cc);
        }
    }
    void push(int x)
    {
        if (a.empty())
        {
            a.push(x);
            aa.push(x);
            return;
        }
        c.push(x);
        cc.push(x);
        update();
    }
    int front()
    {
        return a.top();
    }
    void pop()
    {
        rm.push(a.top());
        a.pop();
        update();
    }
    int size()
    {
        return a.size() + b.size() + c.size();
    }
    bool empty()
    {
        return size() == 0;
    }
};

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n;
    cin >> n;
    Queue q;
    while (n--)
    {
        int op;
        cin >> op;
        if (op == 1)
        {
            int x;
            cin >> x;
            q.push(x);
        }
        else if (op == 2)
        {
            if (q.empty())
            {
                cout << "ERR_CANNOT_POP\n";
                continue;
            }
            q.pop();
        }
        else if (op == 3)
        {
            if (q.empty())
            {
                cout << "ERR_CANNOT_QUERY\n";
                continue;
            }
            cout << q.front() << "\n";
        }
        else
        {
            cout << q.size() << "\n";
        }
    }
}
原文