zoukankan      html  css  js  c++  java
  • POJ 3061 Subsequence

    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

    10 15

    5 1 3 5 10 7 4 9 2 8

    5 11

    1 2 3 4 5

    Sample Output

    2

    5

    题意为:给定长度为n的整数数列以及整数S,求出总和不小于S的连续子序列的长度的最小值,如果解 不存在,输出0.

    先求出sum[i],从第1个数到第i个数的区间和,每次固定一个开始查找的起点sum[i],  然后采用二分查找找到 sum[i] + S 的位置,区间长度即为(末位置-(起始位置-1)),用ans保存过程中区间的最小值。时间复杂度 0(nlogn)

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    int x[100005];
    int n,m;
    int main()
    {
        while(scanf("%d%d",&n,&m)==2){
            x[0]=0;
            int t;
            for(int i=1;i<=n;i++){
                scanf("%d",&t);
                x[i]=x[i-1]+t;
            }
            int ans=n+2;
            for(int i=1;i<=n;i++){
                int j=lower_bound(x,x+n,x[i]-m)-x;
                    if(j>0)ans=min(ans,i-j+1);
            }
            if(ans==n+2)printf("0");
            else printf("%d",ans);
            puts("");
        }
     return 0;
    }
    View Code
  • 相关阅读:
    作业12:字典dict讲解及增删改查等操作
    作业11:元祖及元祖的嵌套
    作业10:列表的嵌套
    作业09:列表的增删改查
    什么数据类型
    作业08:字符串操作
    Visual Studio Code 写Python 代码
    Python——面向对象(初级篇)
    Python 学习第三部分函数——第一章函数基础
    Python3 字典
  • 原文地址:https://www.cnblogs.com/demodemo/p/4716091.html
Copyright © 2011-2022 走看看