滑动窗:Subsequence

来源:互联网 发布:ui设计软件下载 编辑:程序博客网 时间:2024/06/05 11:15
Subsequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 17321 Accepted: 7373

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

Source

Southeastern Europe 2006

跟上一道滑动窗的原理一样,不过略有差别。代码如下:

#include<stdio.h>#include<iostream>#include<algorithm>#include<string.h>#include<math.h>using namespace std;typedef long long LL;const int N=1e5+10;LL s[N];int main(){    int m,n;    LL k;    scanf("%d",&m);    while(m--)    {        memset(s,0,sizeof(s));        int j=1,tmp=1e5,flag=0;        long long ans=0;        scanf("%d%lld",&n,&k);        for(int i=1; i<=n; i++) scanf("%lld",&s[i]);        for(int i=1; i<=n; i++)            if(s[i]>=k)            {                printf("%d\n",1);                flag=1;                break;            }        if(flag) continue;        for(int i=1; i<=n; i++)        {            if(i!=1)  ans-=s[i-1];            if(ans>=k)            {                tmp=min(j-i,tmp);                continue;            }            for(; j<=n; j++)            {                if(ans<k) ans+=s[j];                else  break;            }            if(ans>=k)            tmp=min(j-i,tmp);        }        if(tmp!=1e5) printf("%d\n",tmp);        else  printf("0\n");    }}


原创粉丝点击