POJ:Subsequence

来源:互联网 发布:代理商域名转到阿里云 编辑:程序博客网 时间:2024/06/05 07:30

题目:

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

题目要求:

第一行输入测试样例的数目,第二行第一个数字输入数组的长度,第二个数字输入S,第三行输入这个数组。输出其连续的子序列使其和值大于S的序列的最小长度。

思路:

求最长的符合要求的序列的长度,用取尺法。
1。从头到后扫描这个序列。
2.当子序列和小于S时,将数组的下一个元素加入子序列。
3。当子序列和大于S时,将子序列的第一个元素从子序列里面删除。
4.遍历整个序列,找到最小的满足要求的序列长度。
提示:这里用到了队列的概念。

#include<iostream>#include<cstring>using namespace std;#define MAX 100000//数组的最长长度#define INF 99999999//无穷大int A[MAX];//数组int main(){    int T;    cin>>T;    int N,S;    int sum,ans;    //子序列的总和。    int head,tail;    //队列的头尾节点    int flag;    //标记数字。    //当在循环中不再进行加一减一的操作时,说明这个序列已经遍历完毕。    int min;    while(T--)    {        cin>>N>>S;        memset(A,0,sizeof(A));        //每次都要初始化数组一次        sum=0;        ans=INF;        //这里初始化ans必须初始化为无穷大。        //千万不能初始化为零        //每次只向后扫描一个节点,所以前几次ans的值都是其初始值,        //如果其初始值是零的话,min的值永远只能是零,因为没有序列的长度是比零小  的                 int i;        min=INF;        //最小值初始化为零不解释。        for(i=0;i<N;i++)        {            cin>>A[i];        }        //输入        head=0;        tail=0;        //初始化子序列的头尾节点        sum=A[0];        while(head<=tail)        //头节点必须在尾节点的后面        {            flag=1;//flag的作用到序列的最后几个元素中才会看出来            //读者可以自己模拟一下。            if(sum<S&&tail<=N){            //保证不会越界            tail++;            sum=sum+A[tail];            flag=0;            }//加一            else{                sum=sum-A[head];                head++;                flag=0;            }//减一            if(flag)break;            if(sum>=S)            {                ans=tail-head+1;             if(min>ans)                min=ans;            }        }        if(min!=INF)     cout<<min<<endl;     else        cout<<0<<endl;        //造成不断WA原因,没考虑整个数组的和都比S小的情况。    }return 0;}
原创粉丝点击