POJ3061 Subsequence (追逐法)

这篇博客详细解析了POJ3061的Subsequence问题,通过追逐法求解,适合入门级程序员锻炼算法思维。文章提供了Input和Output的格式说明,并附带Sample Input和Sample Output示例,帮助理解题意。
摘要由CSDN通过智能技术生成


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

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

Sample Output

2
3
 
题目大意:输入一组数,求一个区间[x,y],使区间中的数严格大于S,求区间的最短长度。(若不存在该区间,则输出0)
暴力铁定超时,追逐法也是一种维护区间信息的一种有效手段。开始定区间左界右界left,right,求区间和后若区间和大于S,left--,计算长度,若小于S,right++。扫出最短长度。(时间复杂度O(n),两个指针各自最多走n次)
 
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int a[100002];

int main()
{
    long long t,ii,n,s,i,right,left,sum,leng,ans,flag;
    scanf("%lld",&t);
    for (ii=0;ii<=t-1;ii++)
    {
        memset(a,0,sizeof(a));
        scanf("%lld%lld",&n,&s);
        for (i=0;i<=n-1;i++)
        {
            scanf("%d",&a[i]);
        }
        ans=9999999;
        sum=0;
        left=0;
        right=0;
        sum=sum+a[left];
        flag=0;
        while(1)
        {
            if (right==n)
            {
                break;
            }
            else if (sum<=s)
            {
                right++;
                sum=sum+a[right];
            }
            else if (sum>s)
            {
                flag=1;
                leng=right-left+1;
                if (leng<ans)
                {
                    ans=leng;
                }
                sum=sum-a[left];
                left++;
            }
        }
        if (flag==0)
        {
            printf("0\n");
        }
        else
        {
            printf("%lld\n",ans);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值