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.
Sample Input
10 15
5 1 3 5 10 7 4 9 2 8 5 11
12345
Sample Output
2 3
/* UVALive2678 UVA1121 Subsequence */
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100000;
int prefixsum[N+1];
int main()
{
int n, s, val, ans;
while(cin >> n >> s) {
// 输入数据,计算前缀和
prefixsum[0] = 0;
for(int i=1; i<=n; i++) {
cin >> val;
prefixsum[i] = prefixsum[i - 1] + val;
}
if(prefixsum[n] < s)
ans = 0;
else {
ans = n;
for(int i=0; prefixsum[i] + s < prefixsum[n]; i++) {
int pos = lower_bound(prefixsum + i, prefixsum + n, prefixsum[i] + s) - prefixsum;
ans = min(ans, pos - i);
}
}
cout << ans << endl;
}
return 0;
}
该程序接收一个包含N个正整数的序列及一个正整数S,找出序列中连续子序列的最小长度,使得子序列之和大于等于S。通过计算前缀和,并使用二分查找来优化搜索过程。当前缀和小于S时,答案为0;否则,找到第一个使子序列和大于S的位置,更新答案为当前子序列长度。

被折叠的 条评论
为什么被折叠?



