【算法技巧】尺取法 POJ 3061 Subsequence

Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 11832   Accepted: 4967

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

Source

Southeastern Europe 2006

题意:

给定长度为n的是咧整数a0,a1,...,an-1,以及整数S,求出总和不小于S的连续子序列的长度的最小值。如果不存在输出0。

限制条件:

10 < N < 100 000,S < 100 000 000

the sum of which is greater than or equal to S.

尺取法:

考虑从s开始的最短子序列a[s],a[s+1],a[s+2],.....,a[t]满足sum(s,t)>=S,若该序列的起始位置后移一位,则有,a[s+1],a[s+2],...,a[t],

此时若sum(s+1,t)>=S仍然成立,则s+1开始的最短子序列长度就为t-s,s的位置可以继续往后移动;若sum(s+1,t)<S,此时t必须向后移动一重新构成sum(s+1,t')>=S,保证t最小,以s+1为开始的最短子序列长度就是t'-s,得到的新序列又可以重复进行这样操作,最后去最小区间长度就是答案。

尺取法,因为起点下标s,与终点下标t的移动很像尺蠖(chǐ huò)虫的移动而得名,能在O(n)复杂度内解决上述此类问题。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<map>
#include<string>
#include<queue>
#include<vector>
#include<list>
//#pragma comment(linker,"/STACK:1024000000,1024000000")
using namespace std;
#define INF 0x3f3f3f3f
int n,S;
int a[100005];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&n,&S);
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);

        int ans=INF,sum=0;
        int s=0,t=1;
        for(;;)
        {
            while(sum<S&&t<=n) sum+=a[t++];
            if(sum<S) break;
            ans=min(ans,t-s);
            sum-=a[s++];
        }
        if(ans!=INF) printf("%d\n",ans);
        else puts("0");
    }
    return 0;
}


你可能感兴趣的:(【算法技巧】尺取法 POJ 3061 Subsequence)