Recaman's Sequence
Time Limit:3000MS Memory Limit:60000K
Total Submit:2885 Accepted:1071
Description
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
Source
Shanghai 2004 Preliminary
#include <stdio.h>
#define A_SIZE 500000
#define REC_SIZE 5000000
long a[A_SIZE+10];
int rec[REC_SIZE+10];
int main()
{
long p;
for (p=0;p<REC_SIZE;p++)
rec[p]=0;
a[0]=0;
long m;
for(m=1;m<A_SIZE;m++)
{
a[m]=a[m-1]-m;
if( (a[m] <= 0) || rec[a[m]] == 1 ){
a[m]=a[m-1]+m;
}
rec[a[m]]=1;
}
long n=1;
while( scanf("%d",&n) )
{
if( n == -1 )break;
printf("%ld ",a[n]);
}
}
#include <iostream>
using namespace std;
#define RSIZE 5000000
#define ASIZE 500000
bool rec[RSIZE];
long a[ASIZE];
int main()
{
long i;
for (i=0;i<RSIZE;i++)
rec[i]=false;
for (i=0;i<ASIZE;i++)
a[i]=0;
a[0]=0;
for (i=1;i<ASIZE;i++)
{
a[i]=a[i-1]-i;
if(a[i]<=0 || rec[a[i]]==true)
a[i]=a[i-1]+i;
rec[a[i]]=true;
}
long n;
while(cin>>n)
{
if(n==-1)return 0;
cout<<a[n]<<endl;
}
return 0;
}
本文介绍了一种通过编程实现Recaman数列的算法,并提供了两种不同的C++代码实现方案,旨在帮助读者理解Recaman数列的定义及其计算方法。

548

被折叠的 条评论
为什么被折叠?



