求解一道ACM习题,北大OJ2081

DescriptionTheRecaman'ssequenceisdefinedbya0=0;form>0,am=am−1−mifthersult... 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.
展开
 我来答
wk23415
2011-07-16 · TA获得超过1005个赞
知道小有建树答主
回答量:621
采纳率:0%
帮助的人:825万
展开全部
题意:
定义 a0 = 0 ;当m>0时,am = am-1 -m;如果am <1或者前面出现过am = am-1 + m.输入k,求出ak。

解法:
按所给的递推公式做就可以了。

代码:
#include<stdio.h>
#include<string.h>
int a[500005];
bool f[3012505];
void init()
{
int i;
memset(f,0,sizeof(f));
a[0] = 0;
for(i=1;i<=500000;i++){
if(a[i-1]-i > 0 && ! f[a[i-1]-i]){
a[i]=a[i-1]-i;
f[a[i-1]-i] = 1;
}
else{
a[i]=a[i-1]+i;
f[a[i-1]+i]=1;
}

}
}
int main()
{
int k;

init();
while(scanf("%d",&k),k!=-1){
printf("%d\n",a[k]);
}
return 0;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式