Subsequence UVAlive 2678(尺取法)

题目链接

https://vjudge.net/problem/UVALive-2678

题目

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.

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

题意

给定一个长度为N的整数序列,和一个值S,求最小的连续区间长度使得该区间之和大于等于S。

分析

尺取法:反复推进区间的开头和末尾
先推进区间末尾,使区间满足条件,即区间之和大于等于S;然后推进区间开头,使区间不满足条件;如此反复进行即可得出答案。
因为区间末尾顶多变化N次,区间开头变化的次数总小于等于区间末尾的变化次数,所以时间复杂度O(N)。

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f

using namespace std;

const int maxn=1e5+100;
int N,S,a[maxn],ans,sum;

int main()
{
    while(~scanf("%d%d",&N,&S))
    {
        memset(a,0,sizeof(a));
        for(int i=1;i<=N;i++)
            scanf("%d",&a[i]);
        sum=a[1],ans=INF;
        int i=1,j=1;
        //尺取法
        while(i<=N && j<=N)
        {
            //推进区间的开头
            while(sum<S && j<=N) j++,sum+=a[j];
            if(sum<S) break;

            ans=min(ans,j-i+1);

            //推进区间的末尾
            do
            {
                sum-=a[i++];
                if(sum>=S)
                {
                    ans=min(ans,j-i+1);
                }

            }while(sum>=S && i<=N);

        }
        printf("%d\n",ans==INF?0:ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值