题目大意:给你n个数, 让你问你最长的满足要求的区间有多长,区间要求:MAX - MIN >= m && MAX - MIN <= k
思路:单调队列维护递增和递减,在加入数值的过程中更新答案。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define pii pair<int,int> #define piii pair<int, pair<int,int> > using namespace std; const int N = 1e5 + 7; const int M = 10 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-6; int n, m, k, head1, head2, rear1, rear2; int sk1[N], sk2[N], a[N]; void init() { head1 = head2 = 0; rear1 = rear2 = 0; } int main() { while(scanf("%d%d%d", &n, &m, &k) != EOF) { init(); for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); } int ans = 0, now = 1; for(int i = 1; i <= n; i++) { while(head1 < rear1 && a[sk1[rear1 - 1]] < a[i]) rear1--; while(head2 < rear2 && a[sk2[rear2 - 1]] > a[i]) rear2--; sk1[rear1++] = i; sk2[rear2++] = i; while(head1 < rear1 && head2 < rear2 && a[sk1[head1]] - a[sk2[head2]] > k) { if(sk1[head1] < sk2[head2]) now = sk1[head1++] + 1; else now = sk2[head2++] + 1; } if(head2 < rear2 && head2 < rear2 && a[sk1[head1]] - a[sk2[head2]] >= m) { ans = max(ans, i - now + 1); } } printf("%d ", ans); } return 0; } /* */