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.
 
SampleInput
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
SampleOutput
2
3

双指针 :即用两个指针记录位置 从左往右开始寻找 找到符合条件的就停止 然后记录(用尺子去量的意思一样)
#include <stdio.h>
#define INF 0x3f3f3f3f///表示无穷大,所以要把一段内存全部置为无穷大,我们只需要memset(a,0x3f,sizeof(a))。
int a[100010];
int min(int x,int y)
{
    if(x>y)
        return y;
    return x;
}
int main()
{
    int t,n,q,i;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&q);
        for(i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        int ans=INF;
        int l=0,r=0;///左右区间
        int sum=0;
        while(1)
        {
            while(sum<q&&r<n)///向右扩展,找出大于等于q的区间
            {
                sum=sum+a[r];
                r++;
            }
            if(sum<q)///意思是扫完了,结果还是小于q,则说明不存在
                break;
            while(l<=r&&sum>=q)///在所找出的区间中 ,依次去掉最左端,看能否满足sum大于等于q
            {
                sum=sum-a[l];
                l++;
            }
            ans=min(ans,r-l+1);
        }
        if(ans==INF)
        {
            printf("0\n");
        }
        else
        {
            printf("%d\n",ans);
        }
    }
    return 0;
}

 

posted @ 2017-12-28 19:54  star_fish  阅读(132)  评论(0编辑  收藏  举报