• 51nod 1242 斐波那契数列的第N项


    斐波那契数列的定义如下:
     
    F(0) = 0
    F(1) = 1
    F(n) = F(n - 1) + F(n - 2) (n >= 2)
     
    (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...)
    给出n,求F(n),由于结果很大,输出F(n) % 1000000009的结果即可。
    Input
    输入1个数n(1 <= n <= 10^18)。
    Output
    输出F(n) % 1000000009的结果。
    Input示例
    11
    Output示例
    89

    由于n最大有10^18这么大,直接用F(n) = F(n-1)+F(n-2)肯定不行的,这时可以用F(n+m-1) = F(n)*F(m)+F(n-1)*F(m-1)来做。
    我是用递归来做的,当然,要把已经计算出来的值保存下来,不然同一个值会被计算很多次。


     1 #include <stdio.h>
     2 #include <iostream>
     3 #include <map>
     4 #define ll long long
     5 using namespace std;
     6 const int mod = 1000000009;
     7 map<ll,ll> mp;
     8 //f(n+m-1) = f(n)*f(m)+f(n-1)*f(m-1);
     9 ll fic(ll x){
    10     if(x == 1 || x == 2) return 1;
    11     if(x == 0) return 0;
    12     if(mp[x] != 0) return mp[x];
    13     if(x&1LL) {
    14         ll a = x/2LL;
    15         ll ans = ((fic(a+1LL)*fic(a+1LL))%mod+(fic(a)*fic(a)))%mod;
    16         return mp[x] = ans;
    17     }else{
    18         ll a = x/2LL;
    19         ll ans = ((fic(a)*fic(a+1LL))%mod+(fic(a-1LL)*fic(a)))%mod;
    20         return mp[x] = ans;
    21     }
    22 }
    23 int main(){
    24     ll n;
    25     cin >> n;
    26     cout << fic(n) << endl;
    27     return 0;
    28 }
    
    
  • 相关阅读:
    应急响应中find命令总结
    应急响应排查思路
    硬链接与软链接的区别
    Linux开机启动项总结
    android 開發常用網站
    epoll
    Qualcomm platform, the commonly used parameters of charger and battery in device tree file
    why not ovp protection ?
    Performance tuning
    Using adb over wifi
  • 原文地址:https://www.cnblogs.com/xingkongyihao/p/7220516.html
Copyright © 2020-2023  润新知