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

    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

    前缀和+二分or尺取

    二分
    代码:
    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    int t,n,m,s[100001],mi;
    
    int main()
    {
        scanf("%d",&t);
        while(t --)
        {
            scanf("%d%d",&n,&m);
            mi = n + 1;
            for(int i = 1;i <= n;i ++)
            {
                scanf("%d",&s[i]);
                s[i] += s[i - 1];
            }
            for(int i = 1;i <= n;i ++)
            {
                if(s[i] < m)continue;
                int l = 0,r = i,mid;
                while(l <= r)
                {
                    mid = (l + r) / 2;
                    if(s[i] - s[mid] < m)r = mid - 1;
                    else mi = min(mi,i - mid),l = mid + 1;
                }
            }
            if(mi <= n)printf("%d
    ",mi);
            else printf("0
    ");
        }
    }

    尺取

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    int t,n,m,s[100001];
    int main()
    {
        int head,tail,mi;
        scanf("%d",&t);
        while(t --)
        {
            head = tail = 0;
            mi = 200000;
            scanf("%d%d",&n,&m);
            for(int i = 1;i <= n;i ++)
            {
                scanf("%d",&s[i]);
                s[i] += s[i - 1];
            }
            if(s[n] >= m)
            while(tail <= n)
            {
                while(tail <= n && s[tail] - s[head] < m)tail ++;
                while(tail <= n && s[tail] - s[head] >= m)head ++;
                mi = min(mi,tail - head + 1);
            }
            else mi = 0;
            printf("%d
    ",mi);
        }
    }
  • 相关阅读:
    将戴尔台式机的系统刷成Linux Centos7
    如何在Maven构建的Java项目中使用log4j
    mybatis-generator逆向工程自动生成mapper
    Win10改变系统主题颜色,降低对眼睛的刺激
    09、SpringBoot 整合 jdbcTemplate、Mybatis
    08、SpringBoot配置拦截器
    navicat快捷键
    DevOps:从理念到实施
    活到老学到老啊技术人
    Linux上安装java+tomcat+mysql运行环境
  • 原文地址:https://www.cnblogs.com/8023spz/p/9002103.html
Copyright © 2011-2022 走看看