3061.Subsequence
描述
给出N个正整数(10 <N <100 000)的序列,每个正整数小于或等于10000,并且给出正整数S(S <100 000 000)。编写程序以找到序列的连续元素的子序列的最小长度,其总和大于或等于S.
输入
第一行是测试用例的数量。对于每个测试用例,程序必须从第一行读取数字N和S,以间隔分隔。序列的编号在测试用例的第二行中给出,以间隔分开。输入将以文件结尾结束。
输出
对于每种情况,程序必须在输出文件的单独行上打印结果。如果没有答案,则打印0。
Sample Input
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
Sample Output
2
3
尺取法
设sum是当前连续子序列的和,i,j分别是当前连续子序列的始和末,当sum<s,j向前走,当sum>=s,判断并取序列长度的最小,当循环完一轮后,sum仍然小于s,就终止循环。
#include <iostream>
using namespace std;
const int M = 100005;
int nums[M];
int n, s;
int main()
{
int t;
cin >> t;
while (t--)
{
cin >> n >> s;
for (int i = 0; i < n; i++)
{
cin >> nums[i];
}
int res = n + 1, sum = 0;
int i = 0, j = 0;
while (true)
{
while (j<n && sum < s )
{
sum += nums[j];
j++;
}
if (sum < s) //当满足条件时,此时的j是等于n的,已经不存在大于s的子序列了
break;
res = min(res, j - i);
sum -= nums[i++];
}
if (res > n)
res = 0;
cout << res << endl;
}
return 0;
}