0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-12-24 18:31:59 +00:00

P1886 滑动窗口 /【模板】单调队列

R43006059
This commit is contained in:
Baoshuo Ren 2020-12-02 10:09:33 +08:00 committed by Baoshuo Ren
parent 3d372fa347
commit 01b221bea1
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

View File

@ -3,35 +3,80 @@
using namespace std;
struct node {
int key, val;
} a[1000005];
int l, r;
int min, max;
int n, k;
deque<node> q;
node() {
l = r = 0;
min = 0x3f3f3f3f;
max = -0x3f3f3f3f;
}
node(int _l, int _r) {
l = _l;
r = _r;
min = 0x3f3f3f3f;
max = -0x3f3f3f3f;
}
} tr[1000005 << 2];
int n, k, a[1000005];
void pushup(int u) {
tr[u].max = max(tr[u << 1].max, tr[u << 1 | 1].max);
tr[u].min = min(tr[u << 1].min, tr[u << 1 | 1].min);
}
void build(int u, int l, int r) {
tr[u] = node(l, r);
if (l == r) {
tr[u].max = tr[u].min = a[l];
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
pair<int, int> query(int u, int l, int r) {
if (l <= tr[u].l && r >= tr[u].r) {
return make_pair(tr[u].max, tr[u].min);
}
int mid = tr[u].l + tr[u].r >> 1;
pair<int, int> ans, tmp;
ans.first = -0x3f3f3f3f;
ans.second = 0x3f3f3f3f;
if (l <= mid) {
tmp = query(u << 1, l, r);
ans.first = max(ans.first, tmp.first);
ans.second = min(ans.second, tmp.second);
}
if (r > mid) {
tmp = query(u << 1 | 1, l, r);
ans.first = max(ans.first, tmp.first);
ans.second = min(ans.second, tmp.second);
}
return ans;
}
int main() {
cin >> n >> k;
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++) {
a[i].key = i;
cin >> a[i].val;
scanf("%d", &a[i]);
}
// 最小值
for (int i = 1; i <= n; i++) {
while (!q.empty() && a[i].val <= q.front().val) q.pop_front();
q.push_front(a[i]);
while (q.back().key <= i - k) q.pop_back();
if (i >= k) cout << q.back().val << ' ';
build(1, 1, n);
vector<int> ans_min, ans_max;
for (int i = 1; i + k - 1 <= n; i++) {
pair<int, int> tmp = query(1, i, i + k - 1);
ans_max.push_back(tmp.first);
ans_min.push_back(tmp.second);
}
q.clear();
cout << endl;
// 最大值
for (int i = 1; i <= n; i++) {
while (!q.empty() && a[i].val >= q.front().val) q.pop_front();
q.push_front(a[i]);
while (q.back().key <= i - k) q.pop_back();
if (i >= k) cout << q.back().val << ' ';
for (int i = 0; i < ans_min.size(); i++) {
printf("%d ", ans_min[i]);
}
q.clear();
cout << endl;
printf("\n");
for (int i = 0; i < ans_max.size(); i++) {
printf("%d ", ans_max[i]);
}
printf("\n");
return 0;
}