题目:
Description
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
The first line is the number of test cases. 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.if no answer, print 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
题意:给定一个数列和S, 求出总和不小于S的连续子序列的最小长度, 若解不存在则输出零。
题解:经典的技巧——尺取法。从数组开头开始遍历当第一个数小于S时就一直向后加, 一直加到sum >= S时再将第一个数减掉直到sum小于S, 此时再从刚才停止的地方继续向后加, 标记长度的变量要在sum >= S的时候一直更新最小值, 用这种方法将数组遍历完, 即可得到最小长度。
AC代码:
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
int i, j, s, S, n, T, t, ans, sum;
int len[100005];
scanf("%d", &T);
while(T--){
scanf("%d %d", &n, &S);
ans = n + 1;//ans初始化最大值, 然后更新~
s = 0, t = 0, sum = 0;
for(i = 0;i < n;i++)
scanf("%d", &len[i]);
while(1){
while(t < n && sum < S)//子序列增长至 sum >= S
sum += len[t++];
if(sum < S)
break;
ans = min(ans, t - s);
sum -= len[s++];//子序列缩减
}
if(ans > n)
ans = 0;
printf("%d\n", ans);
}
return 0;
}