acm pku 2091 Recaman's Sequence

本文介绍了一种通过编程实现Recaman数列的算法,并提供了两种不同的C++代码实现方案,旨在帮助读者理解Recaman数列的定义及其计算方法。

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;
    
}
注意大数组必须是全局的
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值