part 1. 栈
栈是一种后进先出的结构。
常用操作:
(1)清空(clear)
(2)获取栈内元素个数(size)
(3)判空(empty)
(4)进栈(top)
(5)出栈(pop)
(6)取栈顶元素(top)
注意 :
出栈操作和取栈顶元素操作必须在栈非空的情形下才能使用,因此在使用 pop() 和 top() 函数前必须使用 empty() 函数 判断栈是否为空
题目:单调栈
给定一个长度为 N 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 −1−1。
输入格式
第一行包含整数 N,表示数列长度。
第二行包含 N 个整数,表示整数数列。
输出格式
共一行,包含 N 个整数,其中第 i 个数表示第 i 个数的左边第一个比它小的数,如果不存在则输出 −1−1。
数据范围
1≤N≤10^5
1≤数列中元素≤10^9
输入样例:
5 3 4 2 7 5
输出样例:
-1 3 -1 2 2
代码:
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
#include<queue>
#include<cstring>
#include<sstream>
#include<string.h>
#include<vector>const int N = 1e6 + 10;
using namespace std;
typedef pair<int ,int> PII;int main()
{int n;cin >> n;while (n -- ){int x;scanf("%d", &x);while (tt && stk[tt] >= x) tt -- ;//如果栈顶元素大于当前待入栈元素,则出栈if (!tt) printf("-1 ");//如果栈空,则没有比该元素小的值。else printf("%d ", stk[tt]);//栈顶元素就是左侧第一个比它小的元素。stk[ ++ tt] = x;}return 0;
}
part 2 . 队列
队列是一种先进先出的数据结构,从队尾加入元素,从队首移除元素
常用操作:
(1)清空(clear)
(2)获取队列内元素个数(size)
(3)判空(empty)
(4)入队(push)
(5)出队(pop)
(6)取队首元素(get_front)
(7)取队尾元素(get_rear)
注意:和栈类似,出队操作和取队首,队尾元素操作必须在队列非空的情况的情况下才能使用
题目:滑动窗口
给定一个大小为 n≤106 的数组。
有一个大小为 k 的滑动窗口,它从数组的最左边移动到最右边。
你只能在窗口中看到 k 个数字。
每次滑动窗口向右移动一个位置。
以下是一个例子:
该数组为
[1 3 -1 -3 5 3 6 7]
,k 为 33。
窗口位置 最小值 最大值 [1 3 -1] -3 5 3 6 7 -1 3 1 [3 -1 -3] 5 3 6 7 -3 3 1 3 [-1 -3 5] 3 6 7 -3 5 1 3 -1 [-3 5 3] 6 7 -3 5 1 3 -1 -3 [5 3 6] 7 3 6 1 3 -1 -3 5 [3 6 7] 3 7 你的任务是确定滑动窗口位于每个位置时,窗口中的最大值和最小值。
输入格式
输入包含两行。
第一行包含两个整数 n 和 k,分别代表数组长度和滑动窗口的长度。
第二行有 n 个整数,代表数组的具体数值。
同行数据之间用空格隔开。
输出格式
输出包含两个。
第一行输出,从左至右,每个位置滑动窗口中的最小值。
第二行输出,从左至右,每个位置滑动窗口中的最大值。
输入样例:
8 3 1 3 -1 -3 5 3 6 7
输出样例:
-1 -3 -3 -3 3 3 3 3 5 5 6 7
int a[N], q[N], hh, tt = -1;#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
#include<queue>
#include<cstring>
#include<sstream>
#include<string.h>
#include<vector>const int N = 1e6 + 10;
using namespace std;
typedef pair<int ,int> PII;
int main()
{int n, k;cin >> n >> k;for (int i = 0; i < n; ++ i){scanf("%d", &a[i]);if (i - k + 1 > q[hh]) ++ hh; // 若队首出窗口,hh加1while (hh <= tt && a[i] <= a[q[tt]]) -- tt; // 若队尾不单调,tt减1q[++ tt] = i; // 下标加到队尾if (i + 1 >= k) printf("%d ", a[q[hh]]); // 输出结果}cout << endl;hh = 0; tt = -1; // 重置!for (int i = 0; i < n; ++ i){if (i - k + 1 > q[hh]) ++ hh;while (hh <= tt && a[i] >= a[q[tt]]) -- tt;q[++ tt] = i;if (i + 1 >= k) printf("%d ", a[q[hh]]);}return 0;
}