算法竞赛训练指南, 48 页
注意:
1、尺取法,滑动窗口 [L, R] 使得区间内的数的和 大于等于 s , 然后更新最小的区间差值 R - L + 1
2、无解的时候,输出 0
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MaxN = 100010;
int n, s;
int seq[MaxN];void solve()
{
int ans = n + 1;int sum = 0;int L = 1, R = 1;while(R <= n){
//不断增加R,使得 sum >= s;while(R <= n && sum < s){
sum += seq[R++];}if(sum < s) //一直移动 R 坐标,都找不到 sum >= s 的话,说明此时 所有的最大可能的sum 值 都 小于s, 退出循环{
break;}ans = min(ans, R - L + 1);//坐标L向右移动,使得 sum < swhile(L < R && sum >= s){
ans = min(ans, R - L);sum -= seq[L++]; }}printf("%d\n",ans);
}int main()
{
while(scanf("%d%d", &n, &s) != EOF){
int sum = 0;for(int i = 1; i <= n; ++i){
scanf("%d", &seq[i]);sum += seq[i];}if(sum < s){
printf("0\n");}else{
solve();}}return 0;
}/* 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5 *//* 2 3 */