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

    Subsequence
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 12311   Accepted: 5169

    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

    Source

     
     
     
    解析:尺取法,即反复地推进区间的开头和末尾,求取满足条件的最小区间的方法。主要用于解答求取某个序列满足某种条件的连续的最小区间的问题。可依照以下四个步骤进行:
    1. 初始化左右指针
    2. 不断移动右指针,直到满足条件
    3. 如果步骤2中的条件无法满足,则终止,否则更新结果
    4. 移动左指针,跳到步骤2
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    
    const int INF = 0x7fffffff;
    const int MAXN = 100000+5;
    int a[MAXN];
    int n, s;
    
    void solve()
    {
        //尺取法
        int l = 0, r = 0;   //初始化左右指针
        int sum = 0, res = INF;
        while(1){
            while(r < n && sum < s){   //不断移动右指针,直到满足条件
                sum += a[r++];
            }
            if(sum < s) //条件无法满足,终止
                break;
            res = min(res, r-l);    //更新结果,相应区间为[l, r)
            sum -= a[l++];  //移动左指针
        }
        printf("%d
    ", res == INF ? 0 : res);
    }
    
    int main()
    {
        int t;
        scanf("%d", &t);
        while(t--){
            scanf("%d%d", &n, &s);
            for(int i = 0; i < n; ++i)
                scanf("%d", &a[i]);
            solve();
        }
        return 0;
    }
    

      

  • 相关阅读:
    大牛思考方式
    web面试题大全
    github上最全的资源教程-前端涉及的所有知识体系
    java switch语句注意的事项
    Lucene Payload 的研究与应用
    hive array、map、struct使用
    黑马程序员--正则表达式
    [置顶] 读源码练内功(一):guava之eventbus
    自定义Java Annotations实例以及用Java Reflection来解析自定义的Annotation
    Solr之NamedList 简单介绍与实例解析
  • 原文地址:https://www.cnblogs.com/inmoonlight/p/5750053.html
Copyright © 2011-2022 走看看