尺取法(小白书)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bengshakalakaka/article/details/80079453
Subsequence
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18784   Accepted: 8036

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

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

整体代码思路

(1)起点终点以及综合初始化s=e=sum=0;

(2)只要依然有sum<S,就不断将sum增加ai,并将终点e往后移动1

(3)如果(2)中条件无法满足,说明已经达到最后位置,不能在往后走了,跳出循环

(4)将sum-a[s],即减去当前起始点,将子序列长度缩短再次进行测试

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
#include<set>
using namespace std;
const int MAX_N=100005;
#define inf 1<<23
typedef long long ll;
typedef long long LL;
int a[MAX_N];
int n,S;//n为数组元素个数,S为给出的最大和值
void solve()
{
    int res=n+1;//初始结果设为res为最大值+1
    int s=0,e=0;//起点和终点坐标设置为0
    int sum=0;//连续子序列和
    while(1)
    {
        while(e<n&&sum<S)
        {
            sum+=a[e++];
        }
        if(sum<S)break;
        res=min(res,e-s);
        sum-=a[s++];
    }
    if(res>n)
    {
        res=0;
    }
    printf("%d\n",res);
}
int main()
{
    int t;
    while(scanf("%d",&t)!=EOF)
    {
        while(t--)
        {
            memset(a,0,sizeof(a));
            scanf("%d%d",&n,&S);
            for(int i=0;i<n;i++)
            {
                scanf("%d",&a[i]);
            }
            solve();
        }
    }

    return 0;
}

所谓尺取法:就是形如本题所示通过反复推进区间的开头和末尾,来求取满足条件的最小区间的方法

猜你喜欢

转载自blog.csdn.net/bengshakalakaka/article/details/80079453