【POJ3061】Subsequence

题目大意:给定一个有 N 个正整数的序列,求出此序列满足和大于等于 S 的长度最短连续子序列。

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=1e5+10;

int n,s,a[maxn];

void read_and_parse(){
    scanf("%d%d",&n,&s);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
}

void solve(){
    int l=1,r=1,now=0,ans=n+1;
    while(1){
        while(r<=n&&now<s)now+=a[r++];//不断向右拓展,寻找一个符合条件的解。
        if(now<s)break;//若找不到,结束迭代
        ans=min(ans,r-l);//更新答案
        now-=a[l++];//减少左指针,继续迭代
    }
    if(ans==n+1)puts("0");
    else printf("%d\n",ans);
}

int main(){
    int T;scanf("%d",&T);
    while(T--){
        read_and_parse();
        solve();
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wzj-xhjbk/p/9893496.html