码迷,mamicode.com
首页 > 其他好文 > 详细

Recaman's Sequence_递推

时间:2016-10-07 01:05:19      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

 

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

 

 

【题意】第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_递推

标签:

原文地址:http://www.cnblogs.com/iwantstrong/p/5935059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!