常用技巧精选之尺取法

尺取法:顾名思义,像尺子一样取一段,借用挑战书上面的话说,尺取法通常是对数组保存一对下标,即所选取的区间的左右端点,然后根据实际情况不断地推进区间左右端点以得出答案。之所以需要掌握这个技巧,是因为尺取法比直接暴力枚举区间效率高很多,尤其是数据量大的

时候,所以尺取法是一种高效的枚举区间的方法,一般用于求取有一定限制的区间个数或最短的区间等等。当然任何技巧都存在其不足的地方,有些情况下尺取法不可行,无法得出正确答案。

 

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

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

 

尺取法通常适用于选取区间有一定规律,或者说所选取的区间有一定的变化趋势的情况,通俗地说,在对所选取区间进行判断之后,我们可以明确如何进一步有方向地推进区间端点以求解满足条件的区间,如果已经判断了目前所选取的区间,但却无法确定所要求解的区间如何进一步

得到根据其端点得到,那么尺取法便是不可行的。首先,明确题目所需要求解的量之后,区间左右端点一般从最整个数组的起点开始,之后判断区间是否符合条件在根据实际情况变化区间的端点求解答案。

例题一:poj3061

Subsequence
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 15982 Accepted: 6771

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



思路:sum(i)=a0+a1+...+ai-1

找到区间[s,t)中,a(s)+...+a(t-1)>=S的位置,对于任何的t'>t,都有a(s)+...+a(t')>=S;

所以利用事先求得的sum(i)可以求得:a(s)+a(s+1)+...+a(t)=sum(t)-sum(s)

对于如何确定序列和不小于S的结尾t的位置可以采用二分查找快速确定位置,优化时间。

#include<string.h>
#include<math.h>
using namespace std;
const int maxn=1e5+10;
int a[maxn];
int sum[maxn+1];
int n,S;
void solve()
{
    //计算sum
    for(int i=0;i<n;i++)
        sum[i+1]=sum[i]+a[i];
    if(sum[n]<S)
    {
        printf("0
");
        return;
    }
    int res=n;
    for(int s=0;sum[s]+S<=sum[n];s++)
    {
        //二分搜索求t
        int t=lower_bound(sum+s,sum+n,sum[s]+S)-sum;
        res=min(res,t-s);
    }
    printf("%d
",res);
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
       scanf("%d%d",&n,&S);
        memset(a,0,sizeof(a));
        memset(sum,0,sizeof(sum));
        for(int k=0;k<n;k++)
            cin>>a[k];
        solve();
    }
    return 0;
}

以上代码的时间复杂度是O(nlogn),事实上还可以更优化,时间复杂度是O(n)

void solve()
{
    int res=n+1;
    int s=0,t=0,sum=0;
    for(;;)
    {
        while(t<n&&sum<S)
        {
            sum+=a[t++];
        }
        if(sum<S)break;
        res=min(res,t-s);
        sum-=a[s++];
    }
    if(res>n)
    {
        res=0;
    }
    printf("%d
",res);
}




            
原文地址:https://www.cnblogs.com/bryce1010/p/9387432.html