选数 单调队列
題目描述
有n個數,要在這n個中選擇連續的m個數,使得這m個數中最大值與最小值不之差不超過k,求最大的m。
輸入文件
第一行包含個兩個整數k,n;
第二行n個整數(int以內)
輸出文件
一個整數m
樣例輸入
2 6 1 15 15 15 15 1樣例輸出
4限制與約定
對于30%的數據,n<=10000
對于50%的數據,n<=100000
對于70%的數據,n<=1000000
對于100%的數據,n<=3000000,k<=1000000000
時間限制:1s
空間限制:128MB
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> using namespace std; const int maxn = 3000000 + 10 ; int Max[maxn],Min[maxn],ans,a[maxn]; struct FastIO {static const int S = 1e7;int wpos;char wbuf[S];FastIO() : wpos(0) {}inline int xchar() {static char buf[S];static int len = 0, pos = 0;if (pos == len)pos = 0, len = fread(buf, 1, S, stdin);if (pos == len) exit(0);return buf[pos++];}inline int xuint() {int c = xchar(), x = 0;while (c <= 32) c = xchar();for (; '0' <= c && c <= '9'; c = xchar()) x = x * 10 + c - '0';return x;}inline int xint(){int s = 1, c = xchar(), x = 0;while (c <= 32) c = xchar();if (c == '-') s = -1, c = xchar();for (; '0' <= c && c <= '9'; c = xchar()) x = x * 10 + c - '0';return x * s;}inline void xstring(char *s){int c = xchar();while (c <= 32) c = xchar();for (; c > 32; c = xchar()) * s++ = c;*s = 0;}inline void wchar(int x){if (wpos == S) fwrite(wbuf, 1, S, stdout), wpos = 0;wbuf[wpos++] = x;}/* inline void wint(ll x){if (x < 0) wchar('-'), x = -x;char s[24];int n = 0;while (x || !n) s[n++] = '0' + x % 10, x /= 10;while (n--) wchar(s[n]);wchar('\n');}inline void wstring(const char *s){while (*s) wchar(*s++);}*/~FastIO(){if (wpos) fwrite(wbuf, 1, wpos, stdout), wpos = 0;} } io; inline int read(){char ch = getchar(); int x = 0, f = 1;while(ch < '0' || ch > '9'){if(ch == '-') f = -1;ch = getchar();}while('0' <= ch && ch <= '9') {x = x * 10 + ch - '0';ch = getchar();}return x * f; } int main() {int k,n,c=1;//cin>>k>>n;k = io.xuint();n = io.xuint();for(int i=1;i<=n;i++)a[i]=io.xuint();int minl=1,minr=0,maxl=1,maxr=0;for(int i=1;i<=n;i++){while(maxr>=maxl && a[Max[maxr]] > a[i]) maxr--;while(minr>=minl && a[Min[minr]] < a[i]) minr--;Max[++maxr]=i;Min[++minr]=i;while( a[Min[minl]] - a[Max[maxl]] > k )if( Max[maxl] > Min[minl]) c=Min[minl]+1,minl++;else c=Max[maxl]+1,maxl++;ans=max(ans,i-c+1);}cout<<ans;return 0; }?
轉載于:https://www.cnblogs.com/hfang/p/11239933.html
總結