poj3061 Subsequence【尺取法】

传送门:http://poj.org/problem?id=3061

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 <algorithm>
#include <iostream>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 5;
LL a[maxn];
int main() {
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while (t--) {
        int n;
        LL s;
        cin >> n >> s;
        for (int i = 1; i <= n; i++) cin >> a[i];
        int st = 1, ed = 1, ans = 0x3f3f3f3f;
        LL sum = a[1];
        while (true) {
            while (ed <= n && sum < s) sum += a[++ed];
            if (sum < s) break;
            ans = min(ans, ed - st + 1);
            sum -= a[st++];
        }
        if (ans == 0x3f3f3f3f) ans = 0;
        cout << ans << endl;
    }
    return 0;
}

尺取法一般要求被选取的区间有一定的变化趋势,变大或者变小。我们要能够从当前的的区间推断出下一步应该是右端点前进还是左端点前进。

猜你喜欢

转载自blog.csdn.net/blue_kid/article/details/79658762
今日推荐