POJ 3061 Subsequence ( 尺取法)

题目链接

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

分析:
由于所有的元素都大于零,如果子序列[s,t)满足As+···+At-1>=S,那么对于所有的t<t'一定有As+···+At'-1>=S。此外对于区间[s,t)上的总和来说如果令
sum(i) = A0+A1+···+Ai-1;
那么
As+As-1+···+At-1=sum(t)-sum(s)
那么预先以O(n)的时间计算好sum的话,就可以以O(1)的时间计算区间上的总和。这样一来,子序列的起点确定以后,便可以用二分搜索快速地确定使序列和不小于S的结尾t的最小值。

int b[100009];
int sum[100009];///保存的是前i个元素的和
void solve1()
{
    for(int i=0; i<n; i++)
    {
        sum[i+1]=sum[i]+b[i+1];
    }

    if(sum[n]<S)///解不存在
    {
        printf("0
");
        return ;
    }

    int res=n;
    for(int s=0; sum[s]+S<=sum[n]; s++)
    {
        ///利用二分搜索求出t
        int t=lower_bound(sum+s,sum+n,sum[s]+S)-sum;
        res=min(res,t-1);
    }
    printf("%d
",res);
}

这个算法的时间复杂度比较大,我们可以用尺取法来解决。

尺取法

我们设以As开始总和最初大于S时的连续子序列为As+···+At-1,这时
As+1+···+At-2<As+···+At-2<S

所以从As+1开始总和最初超过S的连续子序列如果是As+1+···+At'-1的话,则必然有t<=t'。利用这一性质便可以设计出如下算法:

1.以 s=t=sum=0初始化
2.只要依然有sum<S,就不断将sum增加At,并将t加1
3.如果(2)中无法满足sum>=S则终止。否则的话,更新res=min(res,t-s)。
4.将sum减去As,s增加1然后回到(2)。

#include<stdio.h>
#include<iostream>
using namespace std;
int n,S,a[100009];

void solve()
{
    int res=n+1;
    int s=0,t=0,sum=0;
    for(;;)
    {
        while(t<n&&sum<S)
        {
            sum+=a[t++];
        }
        if(sum<S)  break;///此时跳出整个for循环,也就意味着当起始点s
        ///逐渐往后移动的时候,剩下的点不能满足和大于S
        res=min(res,t-s);///res表示的是满足和大于S的最小的间距
        sum-=a[s++];
    }
    if(res>n)///也就是说没有满足条件的间距
        res=0;
    printf("%d
",res);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&S);
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        solve();
    }
    return 0;
}

原文地址:https://www.cnblogs.com/cmmdc/p/7209593.html