UVA - 1121 Subsequence

Input
Many test cases will be given. 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.
Sample Input
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
Sample Output
2
3

 

1.非负,和,可以想到累加数组,进一步优化

2.观察复杂度,都在增加,所以为o(n)

#include <cstdio>
#include <algorithm>

using namespace std;

int main() {
    int n, S, A[100000];
    while (scanf("%d%d", &n, &S) == 2) { //注意退出
        int ans = n + 1, j = 0, t = 0;
        for (int i = 0; i < n; ++i)
            scanf("%d", &A[i]);
        for (int i = 0; i < n; ++i) {
            if (i > 0)
                t -= A[i - 1]; //第i个值开始往后的最小序列
            while (t < S and j < n)
                t += A[j++];
            if (t >= S)
                ans = min(ans, j - i);
        }
        printf("%d\n", ans == n + 1 ? 0 : ans);
    }
}

 

posted @ 2017-10-07 16:06  少年啦飞驰  阅读(140)  评论(0编辑  收藏  举报