• Subsequence (POJ


    Problem

    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

    题解: 其实这题我感觉没有完全用到尺取的方法,可能思想有一点,就是从左端开始枚举,如果当前的和是小于m的,就让右端点右移,sum+=a[r],如果一但满足大于等于m,那么就计算一次ans,然后把左端点左移。重复上面直到遍历一遍就可以了。

    #include <iostream>
    #include <cstdio>
    using namespace std;
    typedef long long ll;
    const int maxn = 1000005;
    int a[maxn];
    int main()
    {
        int t,n,m;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d %d", &n,&m);
            for(int i = 0; i < n; i ++)
                scanf("%d",&a[i]);
            int l = 0,r = 0,sum = 0,ans = n + 1;
            while(1)
            {
                while(r<n&&sum<m)
                {
                    sum=sum+a[r];
                    r ++;
                }
                if(sum<m)
                {
                    break;
                }
                ans = min(r-l,ans);
                sum=sum-a[l];
                l++;
            }
            if(ans == n + 1)
            {
                printf("0
    ");
            }
            else
            {
                printf("%d
    ",ans);
            }
        }
        return 0;
    }
    
  • 相关阅读:
    Java 日期时间类
    JavaMail
    PHP连接 SQLSERVER 注意事项(经典中的经典)
    Spring 依赖注入的 几种方式
    ms sql 备份指令
    Struts2 日期类型编辑器 和 struts.xml 的存放路径
    如何将二维数组作为函数的参数传递
    gcc编译
    关于fflush(stdin)的使用与scanf输入缓冲区的问题
    LINUX socket 连接的几个问题
  • 原文地址:https://www.cnblogs.com/lcchy/p/10139466.html
Copyright © 2020-2023  润新知