A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
The first line is the number of test cases. For each test case the program has to read the numbers N and S, separated by an interval, from the first line. The numbers of the sequence are given in the second line of the test case, separated by intervals. The input will finish with the end of file.
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5
2 3
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100000+11],s[100000+11];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(s,0,sizeof(s));
int n,k;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
s[i]=s[i-1]+a[i]; //前缀和
}
if(s[n]<k) //所有和加起来还小于k,肯定不行,直接输出0
{
printf("0\n");
continue;
}
int ans;
ans=lower_bound(s+1,s+n+1,s[1]+k)-s;//s数组由于是叠加起来的,所以按照从小到大的顺序排列,找到第一个大于等于s[1]+k的位置下标
int l=ans-1;
for(int i=2;i<=n;i++)
{
if(s[n]-s[i]<k)
break;
ans=lower_bound(s+1,s+n+1,s[i]+k)-s;
if(ans-i<l)
l=ans-i;
}
printf("%d\n",l);
}
return 0;
}