Description
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.
Input
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.
Output
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
Sample Input
2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5
Sample Output
23
题意:求出总和不小于S的连续子序列长度的最小值。如果解不存在,则输出0;
思路:这道题我用 尺取法来解;
1;另s,i,sum都为0,进行初始化;
2:只要依然有sum<S,就不断的增加a[i];
3;如果(2)中仍无法满足sum>=S则终止,否则的话则更新res=min(res,i-s);
4;将sun-a[s++],然后回到2;
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; int a[110000],n,S; void solve() { int res=n+1; int i=0,s=0,sum=0; for(;;) { while(i<n&&sum<S) { sum+=a[i++]; } if(sum<S) break; res=min(res,i-s); sum-=a[s++]; } if(res>n) res=0; printf("%d\n",res); } int main() { int t,i; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&S); for(i=0;i<n;i++) scanf("%d",&a[i]); solve(); } return 0; }