日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

洛谷P1962 斐波那契数列题解

發(fā)布時間:2025/4/16 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 洛谷P1962 斐波那契数列题解 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

題目背景

大家都知道,斐波那契數(shù)列是滿足如下性質(zhì)的一個數(shù)列:

? f(1) = 1

? f(2) = 1

? f(n) = f(n-1) + f(n-2) (n ≥ 2 且 n 為整數(shù))

題目描述

請你求出 f(n) mod 1000000007 的值。

輸入格式

·第 1 行:一個整數(shù) n

輸出格式

第 1 行: f(n) mod 1000000007 的值

輸入輸出樣例

輸入 #1 復(fù)制

5

輸出 #1 復(fù)制

5

輸入 #2 復(fù)制

10

輸出 #2 復(fù)制

55

說明/提示

對于 60% 的數(shù)據(jù): n ≤ 92

對于 100% 的數(shù)據(jù): n在long long(INT64)范圍內(nèi)。

解析:

\(\displaystyle \begin{array}{{>{\displaystyle}l}} \ 現(xiàn)在我需要求的矩陣是:\\ \begin{bmatrix} f[ i]\\ f[ i-1] \end{bmatrix}\\ 根據(jù)題目中給出的條件:f[ i] =f[ i-1] +f[ i-2]\\ 下一步求f[ i+1]\\ 所以求初始矩陣為\\ \begin{bmatrix} 1 & 1\\ 1 & 0 \end{bmatrix}\\ 對初始矩陣進(jìn)行矩陣快速冪然后輸出a[ 1][ 1] \end{array}\)

#include <cstdio> #include <iostream> #include <cmath> #include <cstring> #include <queue> #include <stack> #define re register #define Max 200000012 #define int long long int n; const int mod=1000000007; struct Mat {int a[3][3];Mat() {memset(a,0,sizeof a);}inline void build() {memset(a,0,sizeof a);for(re int i = 1 ; i <= 2 ; ++ i) a[i][i]=1;} }; Mat operator*(Mat &a,Mat &b) {Mat c;for(re int k = 1 ; k <= 2 ; ++ k)for(re int i = 1 ; i <= 2 ; ++ i)for(re int j = 1 ; j <= 2 ; ++ j)c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;return c; } Mat a; Mat quick_Mat(int x) {Mat ans;ans.build();while(x) {if((x&1)==1) ans = ans * a;a = a * a;x >>= 1;}return ans; } signed main() {scanf("%lld",&n);a.a[1][1]=1;a.a[1][2]=1;a.a[2][1]=1;Mat b;b.a[1][1]=1;b.a[2][1]=1;if(n>=1 && n<=2) {printf("1");return 0;}Mat ans=quick_Mat(n-2);ans=ans*b;printf("%lld",ans.a[1][1]);return 0; }

轉(zhuǎn)載于:https://www.cnblogs.com/handsomegodzilla/p/11299617.html

總結(jié)

以上是生活随笔為你收集整理的洛谷P1962 斐波那契数列题解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。