1 条题解

  • 0
    @ 2026-11-1 19:55:42

    【模板】队列(Queue Template) 题解

    思路分析

    使用数组双指针 head, tail 或 std::queue<int> 模拟先进先出队列。队空时操作 2 输出 ERR_CANNOT_POP 且不移动队首指针,操作 3 输出 ERR_CANNOT_QUERY;操作 4 输出当前元素个数 tail - head。时间复杂度 O(n)O(n)。

    参考代码

    #include <iostream>
    using namespace std;
    
    const int MX = 20005;
    int q[MX];
    
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        if (!(cin >> n)) return 0;
        int head = 0, tail = 0;
        for (int i = 0; i < n; ++i)
        {
            int op;
            cin >> op;
            if (op == 1)
            {
                int x;
                cin >> x;
                q[tail++] = x;
            }
            else if (op == 2)
            {
                if (head == tail) cout << "ERR_CANNOT_POP\n";
                else ++head;
            }
            else if (op == 3)
            {
                if (head == tail) cout << "ERR_CANNOT_QUERY\n";
                else cout << q[head] << "\n";
            }
            else
            {
                cout << (tail - head) << "\n";
            }
        }
        return 0;
    }
    
    • 1

    信息

    ID
    8529
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者