Subsequence

Subsequence

https://ac.nowcoder.com/acm/problem/107658

尺取法

Subsequence

题意:

给你长度为n的序列,找一个连续子序列的和大于等于s,问该子序列的长度最短为多少

思路:

尺取法

用两个变量来代替尺子的两端,我用i代替左端,j代替右端

最开始序列和sum小于s,就让sum加上tr[j],并让j++

当sum-tr[i]大于等于s时,说明序列删一个元素,得到的子序列还满足大于等于s,就更新最小值,进行循环

#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <stdlib.h>
#include <sstream>
#include <map>
#include <set>
using  namespace std;
#define inf 0x3f3f3f3f
#define MAX 150000 + 5
typedef  long long ll ;

inline int IntRead(){
    char ch = getchar();int s = 0, w = 1;
    while(ch < '0' || ch > '9'){
        if(ch == '-') w = -1;
        ch = getchar();}
    while(ch >= '0' && ch <= '9'){
        s = s * 10 + ch - '0';ch = getchar();}
    return s * w;
}
int tr[MAX];
int main()
{
    int n, t, s;
    cin>>t;
    while (t--) {
        cin>>n>>s;
        for(int i = 1; i <= n; ++i){
            cin>>tr[i];
        }
        int  i = 1, sum = 0, minx = 1e9;
        for(int j = 1; j <= n; ++j){
            sum += tr[j];
            while (sum - tr[i] >= s) {
                sum -= tr[i];
                i++;
                minx = min(minx, j - i + 1);
            }
        }
        if(minx == 1e9)//如果没有能让sum大于s的,则minx就不会更新,输出0即可
            cout<<0<<endl;
        else
            cout<<minx<<endl;
    }
    return 0;
}
全部评论

相关推荐

牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
Gaynes:查看图片
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务