链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=9&problem=679&mosmsg=Submission+received+with+ID+1248543
A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integerS(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 toS.
Input
Many test cases will be given. For each test case the program has to read the numbersN andS, 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 there isn't such a subsequence, print 0 on a line by itself.
Sample Input
10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5
Sample Output
2
3
解题思路:
练习库函数lower_bound()的用法:
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置
举例如下:
一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标
则
pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。
pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。
pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。
所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~
返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置
利用前缀和,以减小时间复杂度,感觉刘老师好厉害,算法可以如此有意思,加油。。。
代码:
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxn=100000+5; int A[maxn],B[maxn]; int main() { int n,s; while(scanf("%d%d",&n,&s)!=EOF) { memset(B,0,sizeof(B)); for(int i=1 ;i <= n;i++) { scanf("%d",&A[i]); B[i]=B[i-1]+A[i]; } int ans=n+1; for(int j=1;j <= n;j++) { int i=lower_bound(B,B+j,B[j]-s)-B;//数组地址连续 if(i>0&&i<=j) ans=min(ans,j-i+1); //B[j]-B[i-1] } printf("%d\n",ans==n+1?0:ans); } return 0; }