LA 3029 Subsequence

LA 3029

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

Many test cases will be given. 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.

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

 

题意:给出n个正整数,要求从中选出最短的一个子序列,这个子序列的和要大于或者等于s

思路:这道题主要难度在于时间,数据范围是十的五次方,如果采用传统的O(n^2)算法恐怕会力不从心,因此要想到改变枚举方式,只枚举子序列的终点?

使用前缀合sum[i],那么最开始是设j=0,那么开始枚举sum[i]-sum[j],如果找到一个符合条件的子序列,就尝试逐渐增加j,最后也无需把j置零,因为sum数列是递增的.如果前面有sum[i]-sum[j]符合条件,那么任何大于i的k都符合sum[k]-sum[j]>=s

 

#include <cstdio>
#include <iostream>
using namespace std;
const int maxn=1e5+10;
int sum[maxn];
int main()
{
    int n,k;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
     sum[0]=0;
     int a;
     for(int i=1;i<=n;i++) {scanf("%d",&a);sum[i]=sum[i-1]+a;}
     int j=0;
     int minx=1e9;
     for(int i=0;i<=n;i++)
     {
       if(sum[i]-sum[j]<k) continue;
       while(sum[i]-sum[j]>=k) j++;
       minx=min(i-j+1,minx);
     }
     printf("%d\n",minx==1e9?0:minx);
    }
    return 0;
}
View Code

这段程序的时间复杂度为O(n),因为外层虽然i从1循环到n,而对于每个i都不可能有从1到n的j循环,顶多就是所有i内的j循环加起来等于n次而已

还可以使用二分法查找合适的j,时间复杂度为O(nlogn)

 

#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=1e5+10;
int sum[maxn];
int main()
{
    int n,k;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
     sum[0]=0;
     int a;
     for(int i=1;i<=n;i++) {scanf("%d",&a);sum[i]=sum[i-1]+a;}
     int j=0;
     int minx=1e9;
     for(int i=0;i<=n;i++)
     {
        j=lower_bound(sum,sum+i,sum[i]-k)-sum;
        if(j>0) minx=min(minx,i-j+1);
     }
     printf("%d\n",minx==1e9?0:minx);
    }
    return 0;
}
View Code

PS:使用lower_bound()进行查找,如果所查找的数比数列中所有的数都要小,就会返回数组头位置的前一位,如果查找的数比数列中所有的数都要大,那么就会返回数组尾的后一位,原因想一想二分法的原理就知道了

posted @ 2015-10-28 18:31  江南何采莲  阅读(229)  评论(0编辑  收藏  举报