1. 程式人生 > >【數論】【矩陣加速】[POJ3070]Fibonacci

【數論】【矩陣加速】[POJ3070]Fibonacci

題目描述

In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:

1, 1, 2, 3, 5, 8, 13, 21, 34, …

樣例輸入

0
9
999999999
1000000000
-1

樣例輸出

0
34
626
6875

題目分析

首先我們可以發現Fib的定義為

Fi=Fi1+Fi2那麼我們就有可以發現[F2F1F1F0][1110]
=[F3F2F2F1]
那麼我們就有[F2F1F1F0][1110][1110]=[F4F3F3F2]那麼我們可以發現[1110][1110]=[F3F2F2F1][1110]n=[Fn+1FnFnFn1]然後矩陣快速冪一下就好了

程式碼

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 5;
const int MOD = 10000;
struct Matrix {
    int Ma[MAXN+10][MAXN+10], n, m;
    void
Clear(int u, int un=0, int um=0){ n = un, m = um; for(int i=1;i<=un;i++) for(int j=1;j<=um;j++) Ma[i][j] = 0; if(u) for(int i=1;i<=un;i++) Ma[i][i] = 1; } Matrix operator* (const Matrix& ma) { Matrix ret ; ret.Clear(0
, n, m); for(int i=1;i<=n;i++){ for(int j=1;j<=ma.m;j++){ for(int k=1;k<=ma.n;k++){ ret.Ma[i][j] += Ma[i][k] * ma.Ma[k][j]; ret.Ma[i][j] %= MOD; } } } return ret; } }; Matrix Mpow(Matrix m, int p){ Matrix ret; if(p == 0){ ret.Clear(1, 2, 2); return ret; }else if(p == 1) return m; ret = Mpow(m, p/2); if(p%2 == 0) return ret * ret; return (ret * ret) * m; } int main(){ int n; while(scanf("%d", &n) && ~n ){ Matrix m; m.Clear(0, 2, 2); m.Ma[1][1] = 1; m.Ma[2][1] = 1; m.Ma[1][2] = 1; Matrix ans = Mpow(m, n); printf("%d\n", ans.Ma[1][2]); } return 0; }