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);
        }
    }
  • 相关阅读:
    The 2019 ICPC Asia Shanghai Regional Contest H Tree Partition k、Color Graph
    回溯法、子集树、排列树、满m叉树
    顺时针打印矩阵
    单调递增的数字
    nodejs
    nodejs + express + mangodb 项目搭建
    nodejs + express 项目初始化
    星星评分功能(带小数点的那种,5颗星,10分制)
    easyui 增加删除toolbar 显示异常问题
    sql 外键级联,触发器防删
  • 原文地址:https://www.cnblogs.com/8023spz/p/9002103.html
Copyright © 2011-2022 走看看