Subsequence
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 12078 | Accepted: 5055 |
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
Source
题目翻译:
给定长度为n的数列整数a0,a1,a2,a3 ….. an-1以及整数S。求出综合不小于S的连续子序列的长度的最小值。如果解不存在,则输出0。
给定长度为n的数列整数a0,a1,a2,a3 ….. an-1以及整数S。求出综合不小于S的连续子序列的长度的最小值。如果解不存在,则输出0。
#include<iostream>
#include<cstdio>
using namespace std;
int num[100005];
int main()
{
int t;
cin>>t;
for(int j = 1;j <= t;j ++)
{
int n, s;
cin>>n>>s;
for(int i = 1;i <= n;i ++)
scanf("%d", &num[i]);
int r = 0, l = 0, ans = n + 1, sum = 0;
for(;;)
{
while(sum < s &&r <= n)
{
sum += num[r++];
}
if(sum < s) break;
ans = min(ans, r - l);
sum -= num[l++];
}
if(ans > n)
ans = 0;
cout<<ans<<endl;
}
}
下面介绍尺取法:
假设我们用一组测试数据举例子,即 n=10, S = 15, a = {5,1,3,5,10,7,4,9,2,8}

这幅图便是尺取法怎么“取”的过程了。
整个过程分为4布:
- 1.初始化左右端点
- 2.不断扩大右端点,直到满足条件
- 3.如果第二步中无法满足条件,则终止,否则更新结果
- 4.将左端点扩大1,然后回到第二步
用尺取法来优化,使复杂度降为了O(n)。
最后,再给一个尺取法的定义以便更好理解:返回的推进区间开头和结尾,求满足条件的最小区间的方法称为尺取法。
以上为网上关于尺取法的原理介绍,还是比较好理解的,邢如蚯蚓的爬动。
尺取法例题: