//poj2100//尺取法//Graveyard Design

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

关于尺取法,我觉得这篇博客讲的特别好。
做之前应该思考这四个问题:
1、 什么情况下能使用尺取法? 2、何时推进区间的端点? 3、如何推进区间的端点? 3、何时结束区间的枚举?
这一定是要找一个连续的区间,且在每一次对于选取区间进行判断后,都能明确如何推进区间的端点。用两个游标记录端点,当游标超出合理范围后结束枚举。
http://blog.csdn.net/consciousman/article/details/52348439
要注意的一点是,每找到一个答案后,都要更新左游标,开始下一轮搜索,否则会一直sum=n循环不出去。

#include<stdio.h>
#include<math.h>

__int64 ans[1000],right[1000],left[1000];

int main()
{
    __int64 n,sum=0;
    scanf("%I64d",&n);
    int cnt=0;
    __int64 l=0,r=0;
    __int64 max=(__int64)sqrt(n*1.0);
    while(1)
    {
        while(sum<n)//总和小于给定的数
        {
            r++;//将右游标向右移动一个单位
            sum+=r*r;//加上右端新数,更新总和
        }
        while(sum>n)//总和大于给定的数
        {
            l++;//将左游标向右移动一个单位
            sum-=l*l;//减去左端旧数,更新总和
        }
        if(sum==n)
        {
            cnt++;
            ans[cnt]=r-l;
            right[cnt]=r;
            left[cnt]=l+1;
            l++;//注意!!!一定要有这两行!!!
            sum-=l*l;//在找到一个答案后移动左游标,开始下一轮搜索
            //否则会一直循环不出去,因为sum=n不变
        }
        if(r>max)
            break;
    }
    printf("%d\n",cnt);
    for(int i=1;i<=cnt;i++)
    {
        printf("%I64d ",ans[i]);
        for(__int64 j=left[i];j<right[i];j++)
            printf("%I64d ",j);
        printf("%I64d\n",right[i]);
    }
}

猜你喜欢

转载自blog.csdn.net/lydia_ke/article/details/79413874