列一列(哈希)


题目描述

小W在计算一个数列{A n},其中A 1=1,A 2=2,A n+2=A n+1+A n。尽管他计算非常精准,但很快他就弄混了自己的草稿纸,他找出了一些他计算的结果,但他忘记了这些都是数列中的第几项。

输入描述:

每行包括数列中的一项Ak(k<=100000)。

总行数T<=30。

输出描述:

对于每一项Ak,输出一行包括一个正整数k表示输入中数是数列的第几项。

示例1

输入

2
3
5
8
13

输出

2
3
4
5
6

 1.unsigned long long 会对溢出的数自动取模。
2.首先打表。
3.哈希。(怎么不哈到一起去。。。)
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
typedef long long  ll;

const int inf = 0x3f3f3f3f;
const int moder = 1e9 + 7;
const int MAXN=1000010;
ull a[MAXN];
int main()
{
    a[1] = 1;
    a[2] = 2;
    for(int i=3;i < MAXN;i++) a[i] = a[i-1] + a[i-2];
    char str[MAXN];
    while(~scanf("%s",str))
    {
        ll len = strlen(str);
        ull B = 0;
        for(int i=0;i < len;i++) B = B*10 + (str[i]-'0');

        for(int i=1;i < MAXN;i++)
        {
            if(a[i] == B)
            {
                cout << i << endl;
                break;
            }
        }
    }
    return 0;
}



map写法:
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
typedef long long  ll;

const int inf = 0x3f3f3f3f;
const int moder = 1e9 + 7;
const int MAXN=1000010;
ll a[MAXN];
map<ll,int> mm;
int main() {
    a[1] = 1,a[2] = 2;
    mm[1] = 1,mm[2] = 2;
    for( int i=3; i<=MAXN; i++ ) //打表
    {
        a[i] = a[i-1] + a[i-2];
        mm[a[i]] = i;            //用map使值和对应的位置形成键值对方便查找
    }
    string s;
    while( cin >> s ) 
    {
        ll sum = 0;
        for( int i=0; i<s.length(); i++ ) 
        {
            sum =  sum * 10 + s[i] - '0';
        }
        cout << mm[sum] << endl;
    }
    return 0;
}
转载自: 点击打开链接
有修改。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值