#include <stdio.h>
long max,fuhao;
int stack[1000],top;
void print()
{int i,j,num;
num=0,j=1;
for(i=top;i;i--)
{while(j<(max-stack[i-1]))
{num=num+fuhao;printf("%d ",num);j++;}
num=num-fuhao;
printf("%d ",num);j++;}
while(j<max)
{num=num+fuhao;
printf("%d ",num);
j++;}
printf("\n");}
long getnumber(long sum,long len)
{long sum1;
sum1=(len+1)*len/2;/*求和公式:1+2+...+len;*/
sum1=sum1-sum;
if(sum1&1)return -1;/*if sum1 是奇数,不存在满足条件的数列*/
sum1=sum1/2;
return sum1;}
void first()
{int i;
top=0;
for(i=0;i<1000;i++)stack[i]=0;}
void make1(long sum)
{long min,sum1;
first();
while(top>=0)
{if(!sum){print();top--;sum=sum+stack[top];continue;}
min=0;
if(top>0)min=stack[top-1];
if(min<stack[top])min=stack[top];
min++;
if(min==max){stack[top]=0;top--;sum=sum+stack[top];continue;}
sum1=(min+max)*(max-min-1);
if(sum>sum1){stack[top]=0;top--;sum=sum+stack[top];continue;}
stack[top]=min;
sum=sum-min;
top++;} }
int main()
{long sum,len,sum1;
printf("please input sum and len:\n");
scanf("%ld%ld",&sum,&len);
if(sum<0){sum=-sum;fuhao=-1;}
else fuhao=1;
max=len+1;
sum1=getnumber(sum,len);
if(sum1==-1){printf("no answer\n");getch( );return 0;}
make1(sum1);
getch( );
return 0;}
[此贴子已经被作者于2005-4-3 10:33:46编辑过]