【POJ】3061---Subsequence(二分)

来源:互联网 发布:mac os 照片 存放位置 编辑:程序博客网 时间:2024/05/21 19:39

                                   SubsequencePOJ - 3061

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
210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5
Sample Output
23

 

思路分析:
            (1):题意:找到一个连续子串,该子串所有数据之和大于等于k,并且使该子串长度最小。
            (2):思路:涉及到几个数据之和,就会很自然地想到前缀和哦,用数组s[i]表示前缀和,下标从1开始存,即s[0]=0,s[1]=a[1],s[2]=s[1]+a[2], .....;
                               如果s[n]<k,说明所有数据的和就小于k,那么肯定不符合条件,直接输出0,continue;
                               数组a[i]不一定按照递增顺序,但是都是正整数,所以数组s[i]一定是递增的,是按照一定顺序排列的,所以对于s[i]可以使用二分查找的思路。
            (3):二分关键:关键步骤是lower_bound(s+1,s+n+1,s[i]+k)-s;区间左端点是s[1],右端点是s[n],所以[s+1,s+n+1)前闭后开的区间,返回值ans是
                                       第一个大于等于s[i]+k的位置(因为要使子串长度最小,所以每次循环找到第一个符合条件的就是当前循环的最小,然后每次循环比较找
                                      到最小),说明ans所在位置的s[j]的值减去s[i] 得到的差大于等于k,从s[i]加到s[j]一共加了ans-1个数据,所以子串长度为ans-1;i从1
                                      到n循环,找到最小的ans-1.


代码如下:
#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;}

原创粉丝点击