您的位置:首页 > 产品设计 > UI/UE

POJ 2081 Recaman's Sequence -- from lanshui_Yang

2012-08-10 17:17 309 查看
DescriptionThe 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.InputThe 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.OutputFor each k given in the input, print one line containing ak 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;  // 把出现过的值统统 标记为 1mymap[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]}}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: