[专题一] 栈和队列

栈的应用

单调栈

// 常见模型:找出每个数左边离它最近的比它大/小的数
int tt = 0;
for (int i = 1; i <= n; i ++ )
{
    while (tt && check(stk[tt], i)) tt -- ;
    stk[ ++ tt] = i;
}

深搜模版

boolean DFS(Node cur, Node target, Set<Node> visited) {
    return true if cur is target;
    for (next : each neighbor of cur) {
        if (next is not in visited) {
            add next to visted;
            return true if DFS(next, target, visited) == true;
        }
    }
    return false;
}

队列的应用

单调队列

//窗口中的最小/最大值、找出离i最近的最小或最大的元素
// 取出最小值
dequeue<int> que; //双端队列
int k;
int findmin(int a[]) {
    for(int i = 0; i < N; i++) { // 遍历数组中的每个元素
        if(!que.empty() && que.front() < i - k + 1 ) // 队头超出范围
        {
            que.front_pop(); //则出队队头元素
        }
        while(!que.empty() && a[que.back()] >  a[i]) que.back_pop(); //队尾元素比a[i]大也出队
        que.push_back(i);
        if(i>= k-1) cout << que.front();
    }
}

BFS模版

int BFS(Node root, Node target) {
    Queue<Node> queue;  
    int step = 0;       // number of steps neeeded from root to current node
    // 初始化
    add root to queue;
    // BFS
    while (queue is not empty) {
        step = step + 1;
        // iterate the nodes which are already in the queue
        int size = queue.size();
        for (int i = 0; i < size; ++i) {
            Node cur = the first node in queue;
            return step if cur is target;
            for (Node next : the neighbors of cur) {
                add next to queue;
            }
            remove the first node from queue;
        }
    }
    return -1;          // there is no path from root to target
}

代码与知识点均学习自AcWing:https://www.acwing.com/activity/

原文地址:https://www.cnblogs.com/recoverableTi/p/12247981.html