用一个倍增来做
首先得到前缀和数组sum
然后从1-n遍历起点,如果sum[k+p]-sum[p]满足,p<<=1,否则p>>=1最后得到一个最小的长度
题目代码
要注意让k不要越界
#include<stdio.h> #include<iostream> #include<string.h> using namespace std; typedef long long LL; const int maxn=1e5+7; const int inf=0x3f3f3f3f; LL sum[maxn],s; int n,a[maxn],t; int main(){ scanf("%d",&t); while(t--){ scanf("%d%lld",&n,&s); sum[0]=0; for(int i=1;i<=n;i++){ scanf("%d",&a[i]); sum[i]=sum[i-1]+a[i]; } int minlen=inf; for(int i=1;i<=n;i++){ int k=i-1,p=1,ans=0; while(p){ while(k+p>n)p>>=1; if(sum[k+p]-sum[k]+ans<s){ ans+=sum[k+p]-sum[k]; k+=p; p<<=1; } else p>>=1; } if(k<n)minlen=min(minlen,k-i+2); } if(minlen==inf)printf("0 "); else printf("%d ",minlen); } return 0; }