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.

题目大意


给定一串数字,让你从中找到最短的连续子串使字串中所有元素的和大于等于S,回答长度。


比如给定 1 2 3 4 5 ,S=10,那么 1 2 3 4 或 2 3 4 1 都可以成为大于等于10的最短字串,当然 1 2 3 4 1 也大于等于10,可是其元素个数没有做到最少,而三个连续元素的任意组合不能满足大于等于10。故输出 4 .

思路&代码


二分答案+内层判断,判断的过程中可以使用前缀和优化,当然,不加优化事实上也能AC. 本题像NOIP 借教室 的简化版.

/*Subsequence
Time Limit: 1000 MS Memory Limit: 65536K
Sources: Southeastern Europe 2006*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int T,n,s,a[100005],l,r,mid,ans;

bool ok(){
    int sum=0;
    for(int i=1;i<=mid;i++) sum+=a[i];
    if(sum>=s) return 1;
    for(int i=1;i<=n-mid;i++){
        sum-=a[i];sum+=a[i+mid];
        if(sum>=s) return 1;
    }
    return 0;
}

int main(){
    cin>>T;
    while(T--){
        cin>>n>>s;
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++) cin>>a[i];
            l=1,r=n,ans=0;
        while(l<r){
            mid=(l+r)/2;
            if(ok()){
                r=mid;
                ans=mid;
            }else{
                l=mid+1;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

分类: Problems

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.