poj 2081 Recaman's Sequence

来源:互联网 发布:sql regexp replace 编辑:程序博客网 时间:2024/05/16 05:58

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

20

 

这道感觉最大的收获就是知道了当数组的大小超过限制时~

可以用static将数组定义为全局变量~这样数组的大小就可以大很多~

PS~这只是方便在机子上运行~提交的时候~不加static也一样能过~

刚开始提交的时候一直是RE~后来发现~像这种输出一串固定的数组中数的时候~

不必输入个数就循环一次~可以先把所有的数计算出来存在数组中~

到时候直接输出就行~

 

下面是代码~

#include"stdio.h"
int main()
{
 int n;
 static bool visit[4000000] = {false};
 static int a[500010]={0};
 int i;
 visit[0]=true;
 for(i=1;i<=500000;i++)
 {
  a[i]=a[i-1]-i;
  if(a[i]<=0||visit[a[i]]==true)
   a[i]=a[i-1]+i;
  visit[a[i]]=true;
 }
 while(scanf("%d",&n),n>=0)
 {
  printf("%d\n",a[n]);
 }
 return 0;

}

 

原创粉丝点击