P3512 [POI 2010] PIL-Pilots
显然,随着区间的扩展,极差单调不减。我们可以用单调队列维护区间最大值和最小值。当极差超过 时,不断将区间首项丢弃,直到极差不超过 。
Code
#include<iostream>
#include<deque>
using namespace std;
int k, n, a[(int)3e6+1], ans, t;
deque<int> p, q;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> k >> n;
for(int i = 1; i <= n; ++i) {
cin >> a[i];
while(!q.empty() && a[q.back()] <= a[i]) {
q.pop_back(); //单调递增队列维护最小值
}
while(!p.empty() && a[p.back()] >= a[i]) {
p.pop_back(); //单调递减队列维护最大值
}
q.push_back(i);
p.push_back(i);
while(!q.empty() && !p.empty() && a[q.front()] - a[p.front()] > k) { //极差大于 k 时丢弃首项
if(++t == q.front()) {
q.pop_front();
}
if(t == p.front()) {
p.pop_front();
}
}
if(!q.empty() && !p.empty()) {
ans = max(ans, i - t); //记录长度
}
}
cout << ans;
return 0;
}P2698 [USACO12MAR] Flowerpot S
和前面一样,极差单调不减。对于每个出现的 ,保存最大与最小的 。将这些 排序后,用单调队列维护区间最大与最小的 的位置。若极差达到 ,则不断出队两者中靠前的(若位置相同则同时出队),直到极差小于 。
Code
#include<iostream>
#include<vector>
#include<algorithm>
#include<deque>
using namespace std;
constexpr int IN = 1e6+1;
int n, d, mx[IN], mn[IN], w = 1e9;
bool vis[IN];
vector<int> v(1, 0);
deque<int> p, q;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> d;
while(n--) { //记录出现的 x,保存最大与最小的 y
int x, y;
cin >> x >> y;
if(!vis[x]) {
vis[x] = true;
v.push_back(x);
mx[x] = mn[x] = y;
} else {
mx[x] = max(y, mx[x]);
mn[x] = min(y, mn[x]);
}
}
sort(v.begin() + 1, v.end());
for(int i = 1; i < (int)v.size(); ++i) {
while(!p.empty() && mx[p.back()] <= mx[v[i]]) { //单调递增队列维护最大值
p.pop_back();
}
while(!q.empty() && mn[q.back()] >= mn[v[i]]) { //单调递减队列维护最小值
q.pop_back();
}
p.push_back(v[i]);
q.push_back(v[i]);
while(!p.empty() && !q.empty() && mx[p.front()] - mn[q.front()] >= d) { //极差达到 k 时记录答案,并缩短区间
if(p.front() > q.front()) {
w = min(v[i] - q.front(), w);
q.pop_front();
} else if(p.front() < q.front()) {
w = min(v[i] - p.front(), w);
p.pop_front();
} else {
w = min(v[i] - p.front(), w);
p.pop_front();
q.pop_front();
}
}
}
cout << (w >= 1e8 ? -1 : w);
return 0;
}