POJ 2081 Recaman's Sequence

题目链接: http://poj.org/problem?id=2081

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

注意:

比较大的数组一定要定义为全局变量。否则会出现栈溢出。原因是全局变量分配在数据段中,而如果在main()

函数中分配的话,则其为局部变量,而局部变量是分配在堆栈段中的,栈溢出不见得是递归调用,也可能是局部

变量过大。此题还有一个技巧是用bitset保存值 coll[i] 是否存在在向量中,而不用再依次查找,大大减小了时间复

杂度。

代码如下:

#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<map>
#include<iterator>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<sstream>
#include<bitset>
using namespace std;
const int N = 500010;
vector<int> coll(N);
bool b[N * 10];
int main()
{
    #ifdef ONLINE_JUDGE
    #else
        freopen("D:\\in.txt", "r", stdin);
        freopen("D:\\out.txt", "w", stdout);
    #endif // ONLINE_JUDEG
        coll[0] = 0;
        b[0] = true;
        for (int i = 1; i <= 500000; i++)
        {
            coll[i] = coll[i - 1] - i;
            if (coll[i] > 0 && !b[coll[i]])
            {
                b[coll[i]] = true;
                continue;
            }
            else
            {
                coll[i] = coll[i - 1] + i;
                b[coll[i]] = true;
            }
            
        }
        int n(0);
        while (cin >> n)
        {
            if (-1 == n)
            {
                break;
            }
            cout << coll[n] << endl;
        }
        return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值