题目传送门:Here
来源:Northeastern Europe 2004, Northern Subregion
Time Limit: 10000MS Memory Limit: 64000K
Case Time Limit: 2000MS
Description
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
解析
给一个数,存在连续递增序列的平方和等于此数,并将这些序列按照长度递减顺序独立一行输出,并且每一行的开头要输出序列长度(如题,21,22,23,24平方和等于2030)
某段连续序列满足条件,联想到尺取法。先截取到的长度一定是最长的,但是题目要求统计序列数量,即序列需要保存下来等待输出,所以我开了两个数组进行左右端点的保存(整个序列循环来存处理上比较麻烦,况且没必要)
C语言代码
#include <stdio.h>
int main(void)
{
long long S;
while(~scanf("%lld",&S)) //爆int要开long long
{
int r[5000],l[5000];
long long i=1,j=1,sum=0;
int m,n,cnt=0;
while(1) //尺取代码
{
while(j*j<=S&&sum<S)
sum+=j*j,j++;
if(sum<S) break;
if(sum==S) //满足条件时的处理
{
l[cnt]=i; //保存左端点
r[cnt]=j; //保存右端点
cnt++; //记录序列个数
}
sum-=i*i;
i++;
}
//以下为输出的代码
printf("%d\n",cnt);
for(m=0;m<cnt;m++)
{
printf("%d",r[m]-l[m]);
for(n=l[m];n<r[m];n++)
printf(" %d",n);
printf("\n");
}
}
}
浅谈
尺取的思想理解起来并不困难,抓住左右端点移动的条件就好。做了几道尺取的题目后发现:不满足条件右端点右移(+),否则左端点右移(-)也可记成 满减少加。
(滑稽.jpg)