POJ-2081-Recaman's Sequence-Hash思想解题

本文介绍了一种使用哈希表实现的序列生成算法。该算法通过计算序列元素并将其存入哈希表来避免重复,确保每个元素的唯一性。文章详细展示了如何定义哈希表、检查元素是否存在以及插入新元素的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream> #include <string> #include <vector> using namespace std; const int MAX_K = 500002; const int MOD_VAL = 499991; int a[MAX_K]; vector<int> hash[MOD_VAL]; //hash表项中存储的是一个实际的数 bool isIn(int n) { int key = n % MOD_VAL; for(vector<int>::size_type i = 0; i != hash[key].size(); i++) { if(n == hash[key][i]) return true; } return false; } void pushInHash(int n) { int key = n % MOD_VAL; hash[key].push_back(n); } void computeRec() { a[0] = 0; for(int i = 1; i <= MAX_K; i++) { int t1 = a[i - 1] - i; int t2 = a[i - 1] + i; if(t1 > 0 && !isIn(t1)) a[i] = t1; else a[i] = t2; pushInHash(a[i]); } } int main() { /*先直接求出前500000个ak*/ computeRec(); int k; while(cin >> k, k != -1) { cout << a[k] << endl; } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值