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
2 3
题目大意:输入一组数,求一个区间[x,y],使区间中的数严格大于S,求区间的最短长度。(若不存在该区间,则输出0)
暴力铁定超时,追逐法也是一种维护区间信息的一种有效手段。开始定区间左界右界left,right,求区间和后若区间和大于S,left--,计算长度,若小于S,right++。扫出最短长度。(时间复杂度O(n),两个指针各自最多走n次)
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int a[100002]; int main() { long long t,ii,n,s,i,right,left,sum,leng,ans,flag; scanf("%lld",&t); for (ii=0;ii<=t-1;ii++) { memset(a,0,sizeof(a)); scanf("%lld%lld",&n,&s); for (i=0;i<=n-1;i++) { scanf("%d",&a[i]); } ans=9999999; sum=0; left=0; right=0; sum=sum+a[left]; flag=0; while(1) { if (right==n) { break; } else if (sum<=s) { right++; sum=sum+a[right]; } else if (sum>s) { flag=1; leng=right-left+1; if (leng<ans) { ans=leng; } sum=sum-a[left]; left++; } } if (flag==0) { printf("0\n"); } else { printf("%lld\n",ans); } } return 0; }