ACM常用技巧-尺取法

尺取法:尺取法通常是指对数组保存一对下标(起点、终点),然后根据实际情况交替推进 两个端点直到得出答案的方法,这种操作很像是尺蠖(日文中称为尺取虫)爬行的方式故得名。
使用尺取法时应清楚以下四点:

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

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

下面的题目是《挑战程序设计》书上的题目练习:


A - Subsequence POJ - 3061
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的最小长度。
我们不难想到,我们可以通过对每个起始点进行二分查找,时间复杂度为nlog(n)

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn=100005;
int sum[maxn],n;

int solve(int s)
{
    int ans=maxn;
    for(int i=1;i<=n;i++)
    {
        int t=lower_bound(sum+i,sum+n+1,s+sum[i-1])-sum;
        if(t!=n+1)
        ans=min(ans,t-i+1);
    }
    return ans==maxn?0:ans;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int s;
        scanf("%d%d",&n,&s);
        sum[0]=0;
        for(int i=1;i<=n;i++)
        {
            int num;
            scanf("%d",&num);
            sum[i]=sum[i-1]+num;
        }

        printf("%d\n",solve(s));
    }
}

虽然nlog(n)的时间能过,但是我们还有更快速的方法–尺取法。
通过移动左右指针(下标)得到答案

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn=100005;
int a[maxn],n;

int solve(int s)
{
   int i=1,j=1,ans=maxn,sum=0;
    for(;;)
    {
        while(j<=n&&sum<s)//注意条件
            sum+=a[j++];
        if(sum<s) break;//说明sum不能再大了
        ans=min(ans,j-i);
        sum-=a[i++];
    }
   return ans==maxn?0:ans;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int s;
        scanf("%d%d",&n,&s);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        printf("%d\n",solve(s));
    }
}

B - Jessica’s Reading Problem POJ - 3320
Jessica’s a very lovely girl wooed by lots of boys. Recently she has a problem. The final exam is coming, yet she has spent little time on it. If she wants to pass it, she has to master all ideas included in a very thick text book. The author of that text book, like other authors, is extremely fussy about the ideas, thus some ideas are covered more than once. Jessica think if she managed to read each idea at least once, she can pass the exam. She decides to read only one contiguous part of the book which contains all ideas covered by the entire book. And of course, the sub-book should be as thin as possible.

A very hard-working boy had manually indexed for her each page of Jessica’s text-book with what idea each page is about and thus made a big progress for his courtship. Here you come in to save your skin: given the index, help Jessica decide which contiguous part she should read. For convenience, each idea has been coded with an ID, which is a non-negative integer.

Input
The first line of input is an integer P (1 ≤ P ≤ 1000000), which is the number of pages of Jessica’s text-book. The second line contains P non-negative integers describing what idea each page is about. The first integer is what the first page is about, the second integer is what the second page is about, and so on. You may assume all integers that appear can fit well in the signed 32-bit integer type.

Output
Output one line: the number of pages of the shortest contiguous part of the book which contains all ideals covered in the book.

Sample Input

5
1 8 8 8 1

Sample Output

2

题目分析:

这题和第一题有一些不同,不同的地方就在怎样去移动指针,怎样去记录移动指针后的状态。我一开始是用set容器来储存的,后来发现erase的时候会有问题,因为如果当前有多个知识点的话,我们会把它全部erase掉,所以我们要选择一种可以储存相同知识点数量的容器-map!

#include<iostream>
#include<cstdio>
#include<map>
using namespace std;

const int maxn=1000005;
int a[maxn],n,ideas;
map<int,int> s;

int solve()
{
    map<int,int> t;
    t.clear();
    int i=1,j=1,ans=n;

    for(;;)
    {
        while(t.size()<ideas&&j<=n)
        {
            if(!t.count(a[j]))
                t[a[j++]]=1;
            else
                t[a[j++]]++;
        }
        if(t.size()<ideas)
            break;
        ans=min(ans,j-i);
        int index=a[i++];
        if(t[index]>1)
            t[index]--;
        else
            t.erase(index);
    }
    return ans;
}

int main()
{
    while(~scanf("%d",&n))
    {
        s.clear();
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            if(!s.count(a[i]))
                s[a[i]]=1;
            else
                s[a[i]]++;
        }
        ideas=s.size();
        printf("%d\n",solve());
    }
}

C - Bound Found POJ - 2566
Signals of most probably extra-terrestrial origin have been received and digitalized by The Aeronautic and Space Administration (that must be going through a defiant phase: “But I want to use feet, not meters!”). Each signal seems to come in two parts: a sequence of n integer values and a non-negative integer t. We’ll not go into details, but researchers found out that a signal encodes two integer values. These can be found as the lower and upper bound of a subrange of the sequence whose absolute value of its sum is closest to t.

You are given the sequence of n integers and the non-negative target t. You are to find a non-empty range of the sequence (i.e. a continuous subsequence) and output its lower index l and its upper index u. The absolute value of the sum of the values of the sequence from the l-th to the u-th element (inclusive) must be at least as close to t as the absolute value of the sum of any other non-empty range.
Input
The input file contains several test cases. Each test case starts with two numbers n and k. Input is terminated by n=k=0. Otherwise, 1<=n<=100000 and there follow n integers with absolute values <=10000 which constitute the sequence. Then follow k queries for this sequence. Each query is a target t with 0<=t<=1000000000.
Output
For each query output 3 numbers on a line: some closest absolute sum and the lower and upper indices of some range where this absolute sum is achieved. Possible indices start with 1 and go up to n.
Sample Input

5 1
-10 -5 0 5 10
3
10 2
-9 8 -7 6 -5 4 -3 2 -1 0
5 11
15 2
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
15 100
0 0

Sample Output

5 4 4
5 2 8
9 1 1
15 1 15
15 1 15

题目分析:

这题不能直接用尺取法,原因请看前面所说的条件。我们需要对前缀和进行sort排序后再用尺取法,至于为什么要把sum[0]也sort,我也还不太理解,这里卡了很久,最后看了题解才加上去强行ac的。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

template<class T>
inline T abs(T xx)
{
    return xx>0?xx:-xx;
}

const int maxn=100005;
pair<long long int,long long int> a[maxn];
long long int ans,sum;
long long int l,r;
long long int n,k;
long long int t;

void solve()
{
    ans=0x3fffffffff;
    long long int i,j,s=a[1].first;
    i=j=1;
    while(j<=n&&ans)
    {
        s=a[j].first-a[i-1].first;
        if(abs(s-t)<=ans)
        {
            ans=abs(s-t);
            l=min(a[i-1].second,a[j].second);
            r=max(a[i-1].second,a[j].second);
            sum=s;
        }
        if(s>t)
        {
            i++;
        }
        else if(s<t)
        {
            j++;
        }
        if(j<=i-1)
            j++;
    }
}

int main()
{
    while(~scanf("%lld%lld",&n,&k))
    {
        if(n==k&&n==0)
            break;
        a[0].first=a[0].second=0;
        for(int i=1;i<=n;i++)
        {
            int num;
            scanf("%d",&num);
            a[i].first=a[i-1].first+num;
            a[i].second=i;
        }

        sort(a,a+n+1);

        while(k--)
        {
            scanf("%lld",&t);
            solve();
            printf("%lld %lld %lld\n",sum,l+1,r);
        }
    }
}

D - Sum of Consecutive Prime Numbers POJ - 2739
Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2+3+5+7+11+13, 11+13+17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime
numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20.
Your mission is to write a program that reports the number of representations for the given positive integer.
Input
The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero.
Output
The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output.
Sample Input

2
3
17
41
20
666
12
53
0

Sample Output

1
1
2
3
0
0
1
2

题目分析:

素数打表+尺取法,水题!

#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;

const int maxn=10005;
vector<int> prime;
bool isprime[maxn];

void printPrime()
{
    memset(isprime,true,sizeof(isprime));
    isprime[0]=isprime[1]=false;

    for(int i=2;i<maxn;i++)
    {
        if(isprime[i])
            prime.push_back(i);

        for(int j=0;j<(int)prime.size();j++)
        {
            if(i*prime[j]<maxn)
                isprime[i*prime[j]]=false;

            if(i%prime[j]==0)
                break;
        }
    }
}

int solve(int n)
{
    int ans=0;
    int l=0,r=0;
    int sum=0;
    while(1)
    {
        while(r<prime.size()&&sum<n)
        {
            sum+=prime[r++];
        }
        if(sum==n) ans++;
        if(sum<n) break;
        sum-=prime[l++];
    }
    return ans;
}

int main()
{
    printPrime();
    int n;
    while(~scanf("%d",&n)&&n)
    {
        printf("%d\n",solve(n));
    }
}

E - Graveyard Design POJ - 2100
King George has recently decided that he would like to have a new design for the royal graveyard. The graveyard must consist of several sections, each of which must be a square of graves. All sections must have different number of graves.
After a consultation with his astrologer, King George decided that the lengths of section sides must be a sequence of successive positive integer numbers. A section with side length s contains s 2 graves. George has estimated the total number of graves that will be located on the graveyard and now wants to know all possible graveyard designs satisfying the condition. You were asked to find them.
Input
Input file contains n — the number of graves to be located in the graveyard (1 <= n <= 10 14 ).
Output
On the first line of the output file print k — the number of possible graveyard designs. Next k lines must contain the descriptions of the graveyards. Each line must start with l — the number of sections in the corresponding graveyard, followed by l integers — the lengths of section sides (successive positive integer numbers). Output line’s in descending order of l.
Sample Input

2030

Sample Output

2
4 21 22 23 24
3 25 26 27

题目分析:

根据output可以知道,我们要先输出解的数量,这就要求我们对求得的结果进行储存,我是用vector进行储存的。然后注意剪枝条件,r*r<=n,反正我一开始在这里时间超限一次。

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;

const long long int maxn=(1e14)+5;
const int size=10000;
vector<int> ans[size];
int cnt;

void solve(long long int n)
{
    long long int r,l,sum=0;
    r=l=1;

    while(1)
    {
        while(r*r<=n&&sum<n)
        {
            sum+=r*r;
            r++;
        }
        if(sum<n) break;
        if(sum==n)
        {
            ans[cnt].push_back(r-l);
            for(int k=l;k<r;k++)
               ans[cnt].push_back(k);
            cnt++;
        }
        sum-=l*l;
        l++;
    }
}

int main()
{
    long long int n;
    while(~scanf("%lld",&n))
    {
        for(int i=0;i<size;i++) ans[i].clear();
        cnt=0;
        solve(n);
        printf("%d\n",cnt);
        for(int i=0;i<cnt;i++)
        {
            for(int j=0;j<(int)ans[i].size();j++)
            {
                printf("%d ",ans[i][j]);
            }
            printf("\n");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/QingyingLiu/article/details/80562720