您的位置:首页 > 其它

uvalive 2678

2015-02-09 00:08 357 查看
题意:给出一个长为n的序列,和目标值s,找出最短序列和刚好大于等于目标值,输出序列长度。

题解:枚举起点终点时间复杂度高,可以枚举终点,f[i]表示序列第1个到第i个数字的和,因为f数组递增,可以用lower_bound()找到起点的位置,使复杂度降低。

#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 100005;
int f
;

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva