POJ 2081 Recaman's Sequence -- from lanshui_Yang

Description

The Recaman's sequence is defined by a0 = 0 ; for m > 0, a m = a m−1 − m if the rsulting a m is positive and not already in the sequence, otherwise a m = a m−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 a k.

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 a k to the output.

Sample Input

7
10000
-1

Sample Output

20
18658
题目大意 很简单 这里 就不多说 啦~
但是要 注意 的是,此题采用一般的在线方法 ,很容易TLE,所以 要采用离线做法,即先把数组a[1000000]初始化。
 
 
具体讲解见代码:
 
 
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <map>
using namespace std;
int a[1000000];
int main()
{
    map<int , int> mymap;  //定义map,意在 判断 数据 是否出现过,具体运用如下:
    mymap.clear();
    a[0]=0;
    a[1]=1;
    a[2]=3;
    mymap[a[0]] =1;  // 把出现过的值统统 标记为 1
    mymap[a[1]] =1;
    mymap[a[2]] =1;
    int i;
    for(i=3; i<=500006; i++)
    {
        a[i]=a[i-1]-i;
        if(mymap.find(a[i])!=mymap.end()||a[i]<=0)
        {
            a[i]=a[i-1]+i;
        }
        mymap[a[i]] = 1;
    }
    int k;
    while (scanf("%d",&k)!=EOF)  
    {
        if(k==-1)
            break;
        printf("%d\n",a[k]);  // 初始化数组a[]后,直接输出a[k]
    }
}


你可能感兴趣的:(Integer,input,each,output,Numbers)