POJ 3061 Subsequence

POJ 3061 Subsequence

POJ传送门

洛谷 UVA1121 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,求最短的子序列长度。

题解:

这道题运用了尺取法的思想,关于尺取法的基本知识请参考我的博客:

链接

如果认真学习本人尺取法的博客之后,我想这道题不再具有什么难度。

本人再就题论题地详解一下这道题地思路:

因为是连续子序列,我们一开始先移动右端点,累加sum,如果超过了证明这就是一个合法的子序列。但是我们还要维护最短,所以我们再向右移动左端点,一直枚举到合法范围的最小答案即可。

最后特判可以了。

代码:

#include<cstdio>  
#include<algorithm>  
#include<cstring>  
#define ll long long  
#define INF 1e9  
using namespace std;  
ll a[100010];  
int n,t,ans=INF;  
ll sum,s;  
int main()  
{
    while(~scanf("%d%lld",&n,&s))
    {  
        for(int i=1;i<=n;i++) 
            scanf("%lld",&a[i]);  
        int l=0,r=0;  
        ans=INF;sum=0;
        while(1)
        {
            while(r<n && sum<s) 
                sum+=a[++r];  
            if(sum<s) 
                break;  
            ans=min(ans,r-l);  
            sum-=a[++l];  
        }  
        if(ans==INF) 
            ans=0;
        printf("%d
",ans);  
    }  
    return 0;  
}

注意一下,以上是洛谷AC代码。POJ的输入跟这个不一样,请大家特殊注意一下。

原文地址:https://www.cnblogs.com/fusiwei/p/11313661.html