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
解题思路:这个题可以用二分,但还有一种更优的算法技巧:尺取法,利用两个下标(起点,终点)不断放缩像虫子伸缩爬行一样来爬出一个最优解,即反复地推进区间的开头和结尾,来求取满足条件的最小区间长度。
AC代码一(79ms):尺取法:时间复杂度是0(n)。
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 using namespace std; 5 const int maxn=1e5+5; 6 int t,n,S,sum,st,ed,res,a[maxn]; 7 int main(){ 8 while(~scanf("%d",&t)){ 9 while(t--){ 10 scanf("%d%d",&n,&S);sum=st=ed=0;res=maxn; 11 for(int i=0;i<n;++i)scanf("%d",&a[i]); 12 while(1){ 13 while(ed<n&&sum<S)sum+=a[ed++]; 14 if(sum<S)break;//如果当前序列和小于S,直接退出 15 res=min(res,ed-st); 16 sum-=a[st++];//指针st往右走,减去队首值 17 } 18 if(res>n)res=0; 19 printf("%d ",res); 20 } 21 } 22 return 0; 23 }
AC代码二(94ms):二分法:时间复杂度是O(nlogn)。
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<string.h> 5 using namespace std; 6 const int maxn=1e5+5; 7 int t,n,S,a[maxn],sum[maxn]; 8 int main(){ 9 while(~scanf("%d",&t)){ 10 while(t--){ 11 scanf("%d%d",&n,&S); 12 memset(sum,0,sizeof(sum)); 13 for(int i=0;i<n;++i)scanf("%d",&a[i]),sum[i+1]=sum[i]+a[i]; 14 if(sum[n]<S){puts("0");continue;}//解不存在 15 int res=n; 16 for(int k=0;sum[k]+S<=sum[n];++k){ 17 int ed=lower_bound(sum+k,sum+n+1,sum[k]+S)-sum;//二分查找 18 res=min(res,ed-k); 19 } 20 printf("%d ",res); 21 } 22 } 23 return 0; 24 }