牛客刷题-Day27
牛客刷题-Day27
今日刷题:\(K-O\)
K 简单的数据结构

解题思路
空间换时间:取数据量的二倍空间,中间的索引表示该容器最开始的位置,这样即使操作全是一侧的插入也不会越界。L 队列Q 也是类似的思路,下面就不赘述了。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 50010, M = 200010;
int n, m;
int b[M];
int main() {
int st = M / 2, ed = M / 2 + 1;
scanf("%d%d", &n, &m);
while (m--) {
int op;
scanf("%d", &op);
if (op == 1) {
int a;
scanf("%d", &a);
b[st--] = a;
} else if (op == 2) {
st++;
} else if (op == 3) {
int a;
scanf("%d", &a);
b[ed++] = a;
} else if (op == 4) {
ed--;
} else if (op == 5) {
reverse(b + st + 1, b + ed);
} else if (op == 6) {
printf("%d\n", ed - st - 1);
for (int i = st + 1; i < ed; i++)
printf("%d ", b[i]);
printf("\n");
} else {
sort(b + st + 1, b + ed);
}
}
return 0;
}
M 滑动窗口

解题思路
单调队列的模板题,详见 数据结构1.2-单调队列。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, k, a[N];
int q[N], hh, tt = -1;
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n; i++) {
if (hh <= tt && i - k + 1 > q[hh]) hh++;
while (hh <= tt && a[q[tt]] >= a[i]) tt--;
q[++tt] = i;
if (i >= k - 1) cout << a[q[hh]] << ' ';
}
cout << endl;
hh = 0, tt = -1;
for (int i = 0; i < n; i++) {
if (hh <= tt && i - k + 1 > q[hh]) hh++;
while (hh <= tt && a[q[tt]] <= a[i]) tt--;
q[++tt] = i;
if (i >= k - 1) cout << a[q[hh]] << ' ';
}
return 0;
}
N [USACO 2009 Mar S]Look Up

解题思路
单调栈的模板题,包括题目 O Largest Rectangle in a Histogram 详见 数据结构1.1-单调栈。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, h[N], res[N];
int stk[N], tt; // 每个数右边第一个大于其的数
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &h[i]);
for (int i = n; i; i--) {
while (tt && h[stk[tt]] <= h[i]) tt--;
res[i] = tt ? stk[tt] : 0;
stk[++tt] = i;
}
for (int i = 1; i <= n; i++)
printf("%d\n", res[i]);
return 0;
}
本文来自博客园,作者:Cocoicobird,转载请注明原文链接:https://www.cnblogs.com/Cocoicobird/p/19460609
浙公网安备 33010602011771号