一个很巧妙的方法。
最初定义一个最左索引 l 和最右索引 r 再定义一个sum 将他们都初始化为0。
然后定义一个所求的最小序列长度res值 初始化为n+1。
然后while循环 直到sum超过题目给的s值或者超过数组长度。
在这个过程中r不断++ (扩大右边界)。
这一轮循环过后 r-l 和 res取最小值。
然后sum不是超过了s么,
然后就将它左边界缩小一点(sum-a【l++】)。
然后不断重复上述操作 某一次判定 超出了数组长度但sum值比s值小 就退出循环 。
给大家上一个图就很明白了:
对于题目的样例:
10 15
5 1 3 5 10 7 4 9 2 8
/*
qq:1239198605
ctgu_yyf
*/
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
using namespace std;
int n,s;
int a[100005];
void solve()
{
int res=n+1;//最短序列长度
int l=0,r=0,sum=0;//s 表示左边的索引 t表示右边的索引 sum表示加起来的总和
for(;;)
{
while(r<n&&sum<s)
{
sum=sum+a[r++];
}
if(sum<s)//说明r超过了这个序列 而sum还没有超过s
break;
res=min(res,r-l);
sum=sum-a[l++];//l 往前进一步继续判断
}
if(res>n)
{
res=0;
}
cout<<res<<endl;
}
int main()
{
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
cin>>n>>s;
for(int i=0;i<n;i++)
cin>>a[i];
solve();
}
return 0;
}