其实可以转化成求一对 i,j使 i-j最小,且sum[i]-sum[j] 〉=s
因为sum是递增的,那么sum-s也是递增的
那么可以用单调队列来做
AC代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define MAX 0x3f3f3f3f
int sum[110000], S, N, ans;
int main(){
while( scanf( "%d%d", &N, &S ) != EOF ){
sum[0] = 0;
for( int i = 1; i <= N; i++ ){
scanf( "%d", &sum[i] );
sum[i] += sum[i-1];
}
ans = MAX;
int j = 1;
for( int i = 1; i <= N; i++ ){
if( sum[j-1] > sum[i] - S ) continue;
while( sum[j] <= sum[i] - S ) j++;
ans = min( ans, i - j + 1 );
}
printf( "%d\n", ans == MAX ? 0 : ans );
}
return 0;
}