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);
        }
    }
  • 相关阅读:
    NET Attribute
    net core HttpClient
    Nuget服务器
    JS-防抖节流
    Codeforces,Topcoder,SGU,Timus,ProjectEuler
    并发编程,高速缓存,原子操作,指令重排序
    C编译器的编译过程主要分成四步: (1) 预处理 (2) 编译 (3) 汇编 (4) 连接
    C#--Distinct
    PageRank算法的思想
    ML.NET 发布0.11版本:.NET中的机器学习,为TensorFlow和ONNX添加了新功能
  • 原文地址:https://www.cnblogs.com/8023spz/p/9002103.html
Copyright © 2011-2022 走看看