天天看點

尺取法(小白書)

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;
}
           

所謂尺取法:就是形如本題所示通過反複推進區間的開頭和末尾,來求取滿足條件的最小區間的方法