尺取法小讲
一、尺取法的基本概念
算法描述
尺取法,在Codeforces中它的算法名称叫做Two Pointers,在《挑战程序设计竞赛》一书中,译者直接使用了日文原文的汉字即尺取法,因为该算法的操作很像是尺蠖(日语中称尺取虫)爬行的方式而得名。
尺取法顾名思义,通常是指对数组保存一对下标(起点、终点),然后根据实际情况交替推进两个端点直接得出答案的方法。
基本框架
//Alun版本
int _beg = 0, _end = 0; //需要保存起点和终点
while(1)
{
// 推进终点,可以使用while()持续推进
if() break; //判断能否构成满足条件序列
// do something...
// 推进起点
}
二、尺取法的经典例题
A. POJ 3061 Subsequence
→ 原题传送门
Time Limit:1000MS
Memory Limit: 65536K
Source: Southeastern Europe 2006
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.
大意:给出N个正整数序列(10 < N < 100,000),每一个正整数都小于或等于10,000,接下来会给出一个正整数S (S < 100,000,000)。要求编写一个程序,求出总和不小于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.
大意:第一行为一个整数,表示测试用例的数量。对于每一个测试用例都含有两行输入,首行为两个整数N和S,紧跟着的一行为N个正整数,中间都用一个空格隔开。
Output
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
大意:一行一个测试用例的答案,如果某一用例解不存在,则输出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
思路概要
对于该题来讲,绝对不可能使用暴力枚举攻克,粗略预估一下,暴力枚举需要不断枚举起点和终点,复杂度应该为 O ( n 2 ) O(n^2) O(n2),大致为 1 e 5 2 1e5^2 1e52,显然会造成超时。
那么如何进行优化呢?
这里有两个思路可以选择:
思路一、前缀和 + 二分答案
前缀和的运用可以快速得到某一区间的答案,再利用二分答案的思想不断枚举总和不小于S的连续子序列的长度即可,每次查找的时间复杂度可以降至 O ( l o g n ) O(logn) O(logn)。
思路二、尺取法
虽然前缀和 + 二分答案的做法已经可以通过该题,但是还可以更加高效地求解该题。
假设以 a s a_s as元素开始总和不小于S时的最初连续子序列为 a s + ⋯ + a t a_s + \cdots + a_t as+⋯+at , 此时起点若向前推进一个,出现如下情况:
a s + 1 + ⋯ + a t < a s + ⋯ + a t < S a_{s+1} + \cdots + a_{t} \lt a_s + \cdots + a_{t} \lt S as+1+⋯+at<as+⋯+at<S
这时,可以选择推进终点位置 t t t,直至得到 t ′ t' t′位置使得 a s + 1 + ⋯ + a t ′ ≥ S a_{s+1} + \cdots + a_{t'} \ge S as+1+⋯+at′≥S,比较原序列长度与新序列长度更新答案。
其实,更可以得到,每一次起点向前推进,都应存在 t ≤ t ′ t \le t'