题意:求满足最大元素与最小元素之差在一定范围的连续区间的最大长度。单调队列经典应用。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstdlib> 5 #include <cstring> 6 #include <map> 7 #include <queue> 8 #include <deque> 9 #include <cmath> 10 #include <vector> 11 #include <ctime> 12 #include <cctype> 13 #include <set> 14 15 using namespace std; 16 17 #define mem0(a) memset(a, 0, sizeof(a)) 18 #define lson l, m, rt << 1 19 #define rson m + 1, r, rt << 1 | 1 20 #define define_m int m = (l + r) >> 1 21 #define Rep(a, b) for(int a = 0; a < b; a++) 22 #define lowbit(x) ((x) & (-(x))) 23 #define constructInt4(name, a, b, c, d) name(int a = 0, int b = 0, int c = 0, int d = 0): a(a), b(b), c(c), d(d) {} 24 #define constructInt3(name, a, b, c) name(int a = 0, int b = 0, int c = 0): a(a), b(b), c(c) {} 25 #define constructInt2(name, a, b) name(int a = 0, int b = 0): a(a), b(b) {} 26 27 typedef double db; 28 typedef long long LL; 29 typedef pair<int, int> pii; 30 typedef multiset<int> msi; 31 typedef multiset<int>::iterator msii; 32 typedef set<int> si; 33 typedef set<int>::iterator sii; 34 35 const int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}; 36 const int dy[8] = {0, -1, 0, 1, -1, 1, 1, -1}; 37 const int maxn = 1e6 + 7; 38 const int maxm = 1e5 + 7; 39 const int MD = 1e9 +7; 40 const int INF = 1e9 + 7; 41 42 template<class T> struct MonotoneQueue{ 43 deque<T> Q; 44 MonotoneQueue<T>() { Q.clear(); } 45 void clear() { Q.clear(); } 46 bool empty() { return Q.empty(); } 47 void add_back(T x) { while (!Q.empty() && !(Q.back() < x)) Q.pop_back(); Q.push_back(x); } 48 void pop_front() { Q.pop_front(); } 49 T front() { return Q.front(); } 50 }; 51 52 struct Pair1 { 53 int val, pos; 54 bool operator < (const Pair1 &a) const { 55 return val < a.val; 56 } 57 constructInt2(Pair1, val, pos); 58 }; 59 struct Pair2 { 60 int val, pos; 61 bool operator < (const Pair2 &a) const { 62 return val > a.val; 63 } 64 constructInt2(Pair2, val, pos); 65 }; 66 MonotoneQueue<Pair1> UQ; 67 MonotoneQueue<Pair2> DQ; 68 69 int main() { 70 //freopen("in.txt", "r", stdin); 71 int n, m, k; 72 while (cin >> n >> m >> k) { 73 UQ.clear(); DQ.clear(); 74 int L = 0, ans = 0; 75 for (int i = 0, x; i < n; i++) { 76 scanf("%d", &x); 77 UQ.add_back(Pair1(x, i)); 78 DQ.add_back(Pair2(x, i)); 79 while (DQ.front().val - UQ.front().val > k) { 80 L++; 81 if (UQ.front().pos < L) UQ.pop_front(); 82 if (DQ.front().pos < L) DQ.pop_front(); 83 } 84 if (DQ.front().val - UQ.front().val >= m) ans = max(ans, i - L + 1); 85 } 86 cout << ans << endl; 87 } 88 return 0; 89 }