A - 尺取 POJ - 3061

A - 尺取

POJ - 3061

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

 

题目描述:

输入N个正整数,求一个长度最小的区间使区间和==S,如果不存在则输出0。

分析:

都是正整数,多取一个和就增加,少取一个和就减小。而且是求区间和等于某个数,可以从第一个数区间开始取,如果和小于要求的数S,则向右取一位,如果和大于S,就减掉最左的一位。一直最右边的数取到底,还不符合要求就不存在这个区间。输出0。

代码:

#include<stdio.h>
#include<math.h>
#define MIN(x,y) x<y?x:y;
int main()
{
    int T;
    int n,s;
    int a[100002];
    int fis,end;
    int sum,min;
    scanf("%d",&T);
    while(T--)
    {
        int po=0;
        scanf("%d %d",&n,&s);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            po+=a[i];
        }
        fis=0,end=1;
        sum=a[0];
        min=n;
        if(sum>=s) printf("1\n");
        else if(po<s) printf("0\n");
        else
        {
            while(end<=n)
            {
                if(sum<s)
                {
                    sum+=a[end];
                    end++;
                }
                else
                {
                    min=MIN(min,end-fis);
                    sum-=a[fis];
                    fis++;
                }
            }
            printf("%d\n",min);
        }
        
    }
}
 

posted on 2020-01-13 09:34  Aminers  阅读(116)  评论(0编辑  收藏  举报

导航