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

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

R52294585
This commit is contained in:
Baoshuo Ren 2021-07-02 19:06:57 +08:00 committed by Baoshuo Ren
parent 8c040f9ff7
commit 52f0e4c253
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

View File

@ -2,81 +2,34 @@
using namespace std; using namespace std;
struct node {
int l, r;
int min, max;
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]; int n, k, a[1000005];
deque<int> q_min, q_max;
void pushup(int u) { vector<int> ans_min, ans_max;
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() { int main() {
scanf("%d%d", &n, &k); scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++) { for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]); scanf("%d", &a[i]);
} }
build(1, 1, n); for (int i = 1; i <= n; i++) {
vector<int> ans_min, ans_max; while (!q_max.empty() && a[q_max.back()] < a[i]) q_max.pop_back();
for (int i = 1; i + k - 1 <= n; i++) { while (!q_min.empty() && a[q_min.back()] > a[i]) q_min.pop_back();
pair<int, int> tmp = query(1, i, i + k - 1); q_max.push_back(i);
ans_max.push_back(tmp.first); q_min.push_back(i);
ans_min.push_back(tmp.second); if (q_min.front() < i - k + 1) q_min.pop_front();
if (q_max.front() < i - k + 1) q_max.pop_front();
if (i >= k) {
ans_max.push_back(a[q_max.front()]);
ans_min.push_back(a[q_min.front()]);
}
} }
for (int i = 0; i < ans_min.size(); i++) { for (int i = 0; i < ans_min.size(); i++) {
printf("%d ", ans_min[i]); cout << ans_min[i] << ' ';
} }
printf("\n"); cout << endl;
for (int i = 0; i < ans_max.size(); i++) { for (int i = 0; i < ans_max.size(); i++) {
printf("%d ", ans_max[i]); cout << ans_max[i] << ' ';
} }
printf("\n"); cout << endl;
return 0; return 0;
} }