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

      

  • 相关阅读:
    滑动窗口模板
    交换机命令
    针对织梦程序列表字段内可有可无的显示方法
    dedecms中常见问题修改方法
    redis系列之------字典
    1.InfluxDB-官方测试数据导入
    MYSQL第二课
    centos6.8下hadoop3.1.1完全分布式安装指南
    Mysql—添加用户并授权
    什么是全文检索
  • 原文地址:https://www.cnblogs.com/inmoonlight/p/5750053.html
Copyright © 2011-2022 走看看