標籤:就是 test targe none tin temp 比較 個數 bsp
題目:http://codeforces.com/contest/602/problem/B
題意 :給出一個含有 n 個數的區間,要求找出一個最大的連續子區間使得這個子區間的最大值和最小值的差值不超過 1 ,最後輸出這個子區間的長度。
分析:
因為區間裡面的數只能相差1,我就用fs與fx來表示這個區間是上升區間還是下降區間
如果上升區間的話,遇到滿足條件的也就是加進來區間的數與區間的開頭a[st]相比較,如果是大1或者是相等就en++,直到不滿足條件;
下降區間也是如此。。。
不滿足條件的話st++。。同時還得重新判斷區間的上升還是下降,因為經驗不足,在這裡卡了許久;
AC代碼:
#include<stdio.h>#include<algorithm>using namespace std;int a[110000];int main(){ int n; scanf("%d",&n); for(int i=0 ; i<n ;i++) scanf("%d",&a[i]); int st=0,en=1; int fs=1,fx=1;///標記fs是表示上升,fx表示下降 int maxx=-10; while(en<=n) { int t=a[st]; if(a[en]-t==1&&fs==1) { fx=0; en++; } else if(a[en]-t==-1&&fx==1) { fs=0; en++; } else if(a[en]-t==0) { en++; } else { int temp=en-st; maxx=max(maxx,temp); st++; int i=1; while(a[st]==a[st+i])///判斷下一個區間是fs還是fx i++; if(a[st]-a[st+i]<0) { fs=1; fx=0; } else { fs=0; fx=1; } } if(en==n) { int temp=en-st; maxx=max(maxx,temp); break; } } printf("%d\n",maxx);}
View Code
#333 Div2 Problem B Approximating a Constant Range(尺取法)