Subsequence学习总结

题目描述
A sequence of N positive integers (10 < N < 10^5), each of them not bigger than 10^4, and a positive integer S (S < 10^8) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is not less than  S.

输入
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.

输出
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.

样例输入
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
样例输出
2
3
//此题的思路是已知维持队列中和大于要求的数,然后不断从头先尾枚举贪心就可以了


#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 100005;
int length(int *a,int len,int k) {
    int top = 0,mini = maxn;
    int sum = 0;
    int pos = 0;
    while (top < len) {
        while (sum < k && top < len) {
            sum += a[top++];
        }
        while (sum >= k) {
            mini = min (mini,top-pos);
            sum -= a[pos++];
        }
        if (top==len) break;
    }
    return mini;
}
int main () {
    int T;
 //   freopen("test.in","r",stdin);
    int n,k,sum=0;
    int a[maxn];
    cin >> T;
    while (T--) {
        cin >> n >> k;
        sum = 0;
        for (int i=0;i<n;i++) {
            cin >> a[i];
            sum += a[i];
        }
        if (sum < k) cout << 0 << endl;
        else cout << length(a,n,k) << endl;
    }
}

 

posted @ 2014-02-18 21:20  闪光阳  阅读(177)  评论(0编辑  收藏  举报