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;
}
题解:枚举起点终点时间复杂度高,可以枚举终点,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;
}
相关文章推荐
- UVALive 2678 利用序列的前缀来减少时间复杂度
- UVA live 2678 - Subsequence
- UVALive 2678 大于s的最短子序列和
- (UVALive - 2678) Subsequence(前缀和,优化)
- UVALive - 2678 Subsequence (尺取法)
- UVALive 2678 子序列
- UVALive - 2678 Subsequence 推理
- UVaLive 2678(LA)Subsequence SEERC 2006 题解
- uvalive2678(子序列)
- UVALive2678 UVA1121 Subsequence【前缀和+二分搜索+尺取法】
- UVALive - 2678 Subsequence 尺取法
- UVALIVE 2678
- UVA live 2678 - Subsequence
- UVALive 6712(2013长春区域赛)
- UVALive 7362 Farey (欧拉函数)
- Confusing Date Format UVALive 7711 给定mm-mm-mm格式的时间。年份(1900-1999)只给了后两位数,问有多少种合法的排列使时间正确。
- UVALive 6195 The Dueling Philosophers Problem 强连通缩点+拓扑序
- UVALive 6653 Pattern Locker(组合数学)
- UVALive 5963 (LA 5963) Confusion in the Problem Set 二分图匹配 (或 YY)
- UVALive - 2757 Supermarket 贪心+优先队列