首页 > 代码库 > Recaman's Sequence_递推

Recaman's Sequence_递推

 

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

710000-1

Sample Output

2018658

 

 

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

#include<iostream>#include<stdio.h>#include<string.h>using namespace std;const int N=10000007;int a[500005];bool ha[N];int main(){    memset(a,0,sizeof(a));    memset(ha,false,sizeof(ha));    for(int i=1;i<=500000;i++)    {        if(a[i-1]-i>0&&!ha[a[i-1]-i])        {            a[i]=a[i-1]-i;        }        else            a[i]=a[i-1]+i;        ha[a[i]]=true;    }    int k;    while(~scanf("%d",&k))    {        if(k<0) break;        printf("%d\n",a[k]);    }    return 0;}

 

Recaman's Sequence_递推