题意:给出一个长为n的序列,和目标值s,找出最短序列和刚好大于等于目标值,输出序列长度。
题解:枚举起点终点时间复杂度高,可以枚举终点,f[i]表示序列第1个到第i个数字的和,因为f数组递增,可以用lower_bound()找到起点的位置,使复杂度降低。
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 100005;
int f[N];
int main() {
int n, s, a;
while (scanf("%d%d", &n, &s) == 2) {
f[0] = 0;
int res = N;
for (int i = 1; i <= n; i++) {
scanf("%d", &a);
f[i] = f[i - 1] + a;
}
for (int i = 1; i <= n; i++) {
int j = lower_bound(f, f + i, f[i] - s) - f;
if (j > 0)
res = min(res, i - j + 1);
}
if (res == N)
printf("0\n");
else
printf("%d\n", res);
}
return 0;
}