题目链接: 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.
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.
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;
}