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;
    }
    

      

  • 相关阅读:
    算法习题---3.11换抵挡装置(UVa1588)
    这不是bug,而是语言特性
    Makefile 11——支持头文件目录指定
    Makefile 10——打造更专业的编译环境-huge项目
    Makefile 9——为依赖关系文件建立依赖关系
    Makefile 8——使用依赖关系文件
    FreeRTOS——1
    Makefile 7——自动生成依赖关系 三颗星
    Makefile学习之路6——让编译环境更加有序
    RCC—使用 HSE/HSI 配置时钟 ---时钟树
  • 原文地址:https://www.cnblogs.com/inmoonlight/p/5750053.html
Copyright © 2011-2022 走看看