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
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. If there isn't such a subsequence, print 0 on a line by itself.
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
题目大意:有n个正整数组成的序列,给定正整数S,求长度最短的连续序列,是他们的和大于等于S。
先求前缀和,然后枚举子序列O(n^2)太慢。如果只枚举终点,因为是正整数序列,和递增,所以子序列开始点递增,所以维护子序列和大于S扫描一遍并更新答案就ok了
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <map>
#include <cmath>
#include <string>
#include <queue>
#include <set>
using namespace std;
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#endif
#define S64I(a) scanf(iform, &a)
#define P64I(a) printf(oform, a)
const int INF = 0x3f3f3f3f;
const int maxn = 100000 + 20;
int A[maxn];
int main() {
int n, s;
while(scanf("%d%d", &n, &s) != EOF ) {
for(int i=0; i<n; i++) {
scanf("%d", &A[i]);
}
int ans = INF;
int j = 0;
int t = 0;
for(int i=0; i<n; i++) {
t += A[i];
while(j < i && t-A[j] >= s) {
t -= A[j];
j++;
}
if(t >= s) {
ans = min(ans, i - j + 1);
}
}
if(ans == INF) ans = 0;
printf("%d\n", ans);
}
return 0;
}