Uva 1121 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 

Many test cases will be given. 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 there isn't such a subsequence, print 0 on a line by itself.

Sample Input 

10 15 
5 1 3 5 10 7 4 9 2 8 
5 11 
1 2 3 4 5

Sample Output 

2 
3


计算正整数序列的,最小字串长度,使得该字串和>= S。

一次计算前n个数的和,保存在下标n中,则arr[n] -arr[k]的值就是k-n的字串的和。

从左到右扫描序列,依次作为字串的终点,维护最小值。arr数组是一个递增数列,假设在j位置去的一个满足j--i的子序列,当则任意M>j都有arr[M] - arr[j] > S,要取最小值,则使得j不断趋近于M,因为arr[M] - arr[j] > S,所有只需从j当前位置起开始扫描即可。


 


#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <algorithm>

using namespace std;

const int MAX = 100000 + 5; 
const long MAX_VAL = 1000000000 + 5;

long arr[MAX]; 
int main(int argc, char *argv[])
{
    int n,s;
    
    
    while(scanf("%d%d",&n,&s)!= -1)
    {
        for(int i = 1; i <= n; i++)scanf("%ld",arr + i);
        
        arr[0] = 0;
        for(int i = 1; i <= n; i++)arr[i] += arr[i - 1];
        
        int j = 0,mmin = MAX_VAL;
        for(int i = 1; i <= n; i++)
        {
            if(arr[i] - arr[j] < s)continue;
            
            while(arr[i] - arr[j] >= s)j++;//i 从上一次起始,因为j后移后 必定arr[i] - arr[j] > arr[i - 1] - arr[j] i-j取最小值时  j >=当前值 
                                          //长度尽可能小 j 趋于i 
            mmin = min(mmin, i - j + 1);
        }
        
        if(j == 0)mmin = 0;
        
        printf("%d\n",mmin);
        
    }
    

    
    //system("PAUSE");
    return EXIT_SUCCESS;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值