Subsequence

Subsequence

该题要求的是连续序列,所以有两个方法,一个是是二分加前缀和,复杂度为\(O(nlog(n))\),另一种方法是用尺取法,复杂度为\(O(n)\)

尺取法代码:

// Created by CAD on 2020/2/1.
#include 
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=1e5+5;
int a[maxn];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;cin>>t;
    while(t--){
        int n,s;  cin>>n>>s;
        for(int i=1;i<=n;++i)
            cin>>a[i];
        int head=1,tail=1;
        int sum=a[1],ans=inf;
        while(head<=n){
            while(sum>=s&&tail<=head) ans=min(ans,head-tail+1),sum-=a[tail++];
            sum+=a[++head];
        }
        if(ans==inf)    cout<<0<

你可能感兴趣的:(Subsequence)