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);
        }
    }
  • 相关阅读:
    进程与线程
    Socket函数编程(二)
    socket编程
    subprocess 模块
    异常处理
    模块与包
    【Java基础】String源码分析
    【MySQL】 执行计划详解
    【MySQL】performance schema详解
    【Spring Cloud-Open Feign】使用OpenFeign完成声明式服务调用
  • 原文地址:https://www.cnblogs.com/8023spz/p/9002103.html
Copyright © 2011-2022 走看看