Poj 3061 Subsequence (尺取

来源:互联网 发布:mac 网盘 知乎 编辑:程序博客网 时间:2024/04/30 04:33

尺取法:

顾名思义,像尺子一样取一段,借用挑战书上面的话说,尺取法通常是对数组保存一对下标,即所选取的区间的左右端点,然后根据实际情况不断地推进区间左右端点以得出答案。之所以需要掌握这个技巧,是因为尺取法比直接暴力枚举区间效率高很多,尤其是数据量大的时候,所以尺取法是一种高效的枚举区间的方法,一般用于求取有一定限制的区间个数或最短的区间等等。当然任何技巧都存在其不足的地方,有些情况下尺取法不可行,无法得出正确答案。

使用尺取法时应清楚以下四点:

1、 什么情况下能使用尺取法?
2、何时推进区间的端点?
3、如何推进区间的端点?
4、何时结束区间的枚举?

尺取法通常适用于选取区间有一定规律,或者说所选取的区间有一定的变化趋势的情况,通俗地说,在对所选取区间进行判断之后,我们可以明确如何进一步有方向地推进区间端点以求解满足条件的区间,如果已经判断了目前所选取的区间,但却无法确定所要求解的区间如何进一步得到根据其端点得到,那么尺取法便是不可行的。
首先,明确题目所需要求解的量之后,区间左右端点一般从最整个数组的起点开始,之后判断区间是否符合条件在根据实际情况变化区间的端点求解答案。

下面是Poj 3061 尺取法入门例题

Subsequence

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

210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5

Sample Output

23

Hint

大神的图片 帮助理解这个题的过程
这里写图片描述

题意

给长度为n的数组和一个整数m,求总和不小于m的连续子序列的最小长度;

题解:

尺取法模板

AC代码

/*对着白书抄的代码,很好理解的了*/#include <cstdio>#include <cstring>#include <cmath>#include <queue>#include <stack>#include <map>#include <set>#include <iostream>#include <vector>#include <algorithm>using namespace std;#define ll long longconst int mod = 1e9+7;#define N 100005int arr[N];int main(){    int T;    scanf("%d",&T);    while(T--) {        int n, s, m;        scanf("%d%d",&n,&s);        for(int i = 0;i < n; i++)             scanf("%d",&arr[i]);        int l, r, sum , ans = n+1;        l = r = sum = 0;        while(true) {            while(r<n && sum<s) {                sum += arr[r];                r++;            }            if(sum < s) break;            m = r - l;            if(m > ans)                 m = ans;            ans = m;                //ans就是最短长度             sum -= arr[l++];        //前进的尺取        //  printf("%d\n",ans);         }         if(ans == n+1)             puts("0");        else             printf("%d\n",ans);    }return 0;}
1 0
原创粉丝点击