题意:给一序列整数,求和大于等于S的最短连续子序列长度。
思路:二分枚举长度,求出满足条件的最短长度。
#include<iostream>
#include<string.h>
using namespace std;
int n,s;
int a[100005];
bool judge(int x){
unsigned int temp = 0;
for(int i = 0;i < x;i++)
temp += a[i];
if(temp >= s)
return true;
else{
for(int i = 1;i <= n - x;i++){
temp = temp - a[i - 1] + a[i + x - 1];
if(temp >= s)
return true;
}
return false;
}
}
int main(){
while(cin >> n >> s){
unsigned int count = 0;
for(int i = 0;i < n;i++){
cin >> a[i];
count += a[i];
}
if(count < s){
cout << 0 << endl;
continue;
}
int min = 1,max = n,mid;
while(min < max){
mid = (min + max)/2;
if(judge(mid)){
max = mid;
}
else
min = mid + 1;
}
cout << max << endl;
}
return 0;
}