ZOJ-2421 Recaman's Sequence

The Recaman's sequence is defined by a0 = 0 ; for m > 0, am = am-1 - m if the rsulting am is positive and not already in the sequence, otherwise am = am-1 + m.

The first few numbers in the Recaman's Sequence is 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9... . Given k, your task is to calculate ak.

Input

The input consists of several test cases. Each line of the input contains an integer k where 0 <= k <= 500000. The last line contains an integer -1, which should not be processed.

Output

For each k given in the input, print one line containing ak to the output.

Sample Input

7
10000
-1

Sample Output

20
18658

题意:第m个位置的数是根据第m-1位置的数推出来的如果a[m-1]-m>0,并且a[m-1]-m在前面的序列中没有出现过那么a[m] = a[m-1]-m否则a[m] = a[m-1]+m,a[0]=0。

代码:

#include <stdio.h>
#include <string.h>
int book[5000010],a[500010];

int main()
{
	int i,n;
	memset(a,0,sizeof(a));
	memset(book,0,sizeof(book));
	book[0]=1;
	for(i=1;i<=500010;i++)
	{
		a[i]=a[i-1]-i;
		if(a[i]<0||book[a[i]])
			a[i]=a[i-1]+i;
		book[a[i]]=1;
	}
	while(scanf("%d",&n)!=EOF)
	{
		if(n==-1)
			break;
		printf("%d\n",a[n]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hello_cmy/article/details/81865104