POJ 2081 Recaman's Sequence
来源:互联网 发布:语法分析算法 编辑:程序博客网 时间:2024/05/16 09:39
题目链接: http://poj.org/problem?id=2081
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.
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.
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
2018658
注意:
比较大的数组一定要定义为全局变量。否则会出现栈溢出。原因是全局变量分配在数据段中,而如果在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;}
0 0
- POJ 2081 Recaman's Sequence
- poj 2081 Recaman's Sequence
- POJ 2081 Recaman's Sequence
- poj 2081 :Recaman's Sequence
- poj 2081Recaman's Sequence
- poj 2081 Recaman's Sequence
- POJ 2081 Recaman's Sequence
- POJ-2081:Recaman's Sequence
- POJ-2081-Recaman's Sequence
- poj 2081 Recaman's Sequence
- POJ 2081 Recaman's Sequence
- POJ 2081 Recaman's Sequence
- POJ 2081 Recaman's Sequence
- poj 2081 Recaman's Sequence
- POJ 2081 Recaman's Sequence
- poj 2081【Recaman's Sequence】
- POJ 2081 Recaman's Sequence
- POJ-2081 Recaman's Sequence
- [jimmyzhouj 翻译] Nehe iOS OpenGL ES 2.0教程 --Lesson 02
- 视图的单击,双击,捏合,扫动,旋转,长按等。
- 数据库及JDBC技术
- iOS OpenGL ES2.0教程 Lesson03 旋转
- hdu 1054 最小点覆盖
- POJ 2081 Recaman's Sequence
- 深入学习python (六) 用sched来定时执行任务
- iOS OpenGL ES 2.0教程 Lesson04--3D空间
- EditText 去边框
- Unity3d中MicroPhone的使用
- Linux下C语言的多线程编程学习[写得很好哦]
- java synchronized详解
- java调用存储过程图解
- cabac编码过程的解读