Subsequence

来源:互联网 发布:永恒之塔捏脸数据 编辑:程序博客网 时间:2024/06/06 03:06

题目:

Subsequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 16648 Accepted: 7070

Description

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

210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5

Sample Output

23

心得:

这个书上的算法运行起来 ,感觉像是虫子的蠕动,在蠕动的同时,不断地缩短自己的身长

代码<c++>:

#include<stdio.h>#include<stdlib.h>int m,n,s;int a[100086];void slove();int main(){    scanf("%d",&m);    while(m--)    {        scanf("%d %d",&n,&s);        //printf("你懂的%d   %d",n,s);        for(int i=0; i<n; i++)        {            scanf("%d",&a[i]);        }        slove();return 0;    }}/*x是记录已选数列长度的,只减不增sum 是数列累加的和*/void slove(){    int x=n+1;    int y=0,t=0,sum=0;    while(1)    {        while(t<n&&sum<s)//此处进行累加        {            sum+=a[t++];            //printf("sum的值:%d \n",sum);        }        if(sum<s)//如果整个数列累加完,sum还是小于s,直接判定 答案 为0            break;        x=(x>(t-y))?t-y:x;//t-y为当前选中的数组的长度        //printf("x的值:%d \n",x);        sum-=a[y++];    }    if(x>n)    {        x=0;    }    printf("%d\n",x);}



AC:



原创粉丝点击