poj3061(Subsequence)尺取法

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

很简单的一道题,尺取法就是对数组保存起点和终点,通过根据实际情况交替推进两个端点得到答案。


#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <limits>
#include <new>
#include <utility>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <ctime>
using namespace std;

int a[100010];

int main()
{
    int T;
    cin >> T;
    while (T--)
    {
        int n, S;
        cin >> n >> S;
        for (int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        int ans = n + 1;
        int s = 0, t = 0, sum = 0;
        while (1)
        {
            while (t < n && sum < S)
                sum += a[t++];
            if (sum < S)
                break;
            ans = min(ans, t-s);
            sum -= a[s++];
        }
        if (ans > n)
            ans = 0;
        cout << ans << endl;
    }
    return 0;
}


算法码上来 文章被收录于专栏

公众号「算法码上来」。godweiyang带你学习算法,不管是编程算法,还是深度学习、自然语言处理算法都一网打尽,更有各种计算机新鲜知识和你分享。别急,算法码上来。

全部评论

相关推荐

会员标识
今天 16:28
已编辑
牛客运营
从03年的“北大毕业生卖猪肉”到前段时间上热搜的“北大博士入职城管”,这些年“下沉式就业”现象频繁牵动着大家的视野和目光吧,很吸睛?我觉得并不是,如果你说985大学生XXX,那可能成不了焦点,如果说是北大清华毕业生去当城管,卖猪肉,大家都会讨论一番,无论是谁都知道北大清华的过人之处。但是呢近些年的确有很多985、211名校毕业生选择到基层就业或回老家创业,会不会觉得大财小用?老家的哥哥,因为当时学的专业不是很好,但好在学校不错,一路本硕连读,毕业之后在上海打拼了2年,也攒了一些小钱,随后回村选择科学养鸡,买了很大一块地开始科学方法的养鸡、卖鸡蛋,村里的老人都会议论纷纷,白瞎了家里供你读书,又回...
下午吃泡馍:不是每一个脱下长衫的人在下沉市场重获新生,并不是每一个养猪养鸡的高学历人才都会成功。现实是很多人的“长衫”就是自己为数不多甚至唯一的底牌了,拼尽全力拿到一个不错的学历,这时候主流媒体告诉对方脱下长衫也可以活的精彩,其实真的挺难过的。强者恒强,但是弱者是人群的底色。 本质上是整个市场的问题,没有足够多的增长点,没有足够多的岗位,自上而下没有积极向上的氛围。外企撤出,供应链缺失...在发展的过程中总有阵痛,现阶段可能就是我们承受阵痛的过程。之前在牛客看到一个小伙伴说:时代的一粒灰尘,落在谁的身上,都将是无法承受之重!深有感触。
点赞 评论 收藏
分享
新记话事人:你就和她说去抖音了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务