矩陣快速冪--Fibonacci POJ3070

矩陣快速冪–Fibonacci POJ3070

題目連接
Fibonacci
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 17587 Accepted: 12257
Description

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:

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

An alternative formula for the Fibonacci sequence is
這裏寫圖片描述

Given an integer n, your goal is to compute the last 4 digits of Fn.

Input

The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

Output

For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

Sample Input

0
9
999999999
1000000000
-1
Sample Output

0
34
626
6875
Hint

As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

這裏寫圖片描述
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
這裏寫圖片描述

Source

Stanford Local 2006

解題思路
顯然用遞歸定義肯定不行,即使將遞歸轉化成遞推優化10^18也會超時,所以用到矩陣來轉化
1.顯然常規遞推時間複雜度和空間複雜度都會超
2.當遇到這種問題時顯然是找公式和規律
3.比如f[1][1]=1,f[n][m]=a*f[n-1][m]+b*f[n-1][m-1]當n和m超級大時,顯然要利用公式,找出了楊輝三角
4.進而找出了快速冪求模,組合快速冪求模等
5.這道題沒有公式這是用矩陣快速冪來解決遞推無限大問題

#include<iostream>
#include<memory.h>
#include<stdio.h>
#define N 2
using namespace std;
typedef long long LL;
LL p=1000000009;
LL res[N][N];
void mult(LL res[][N],LL a[][N]){
    LL tem[N][N];
    memset(tem,0,sizeof(tem));
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++){
            for(int k=0;k<N;k++){
                tem[i][j]+=(res[i][k]*a[k][j])%p;
            }
        }
    }
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++){
            res[i][j]=tem[i][j];
        }
    }
    return;
}
void quick_mod(LL a[][N],LL n){
    memset(res,0,sizeof(res));
    for(int i=0;i<N;i++){
        res[i][i]=1;
    }
    while(n){
        if(n&1){
            mult(res,a);
        }
        mult(a,a);
        n>>=1;
    }
    return;
}
int main(){
    LL n;
    LL a[2][2]={{1,1},{1,0}};
    cin>>n;
    quick_mod(a,n-1);
    cout<<res[0][0]%1000000009<<endl;
    return 0;
}
發佈了29 篇原創文章 · 獲贊 11 · 訪問量 9278
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章