首页 > 代码库 > [ACM] POJ 3070 Fibonacci (矩阵幂运算)

[ACM] POJ 3070 Fibonacci (矩阵幂运算)

Fibonacci
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9517 Accepted: 6767

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


解题思路:

题目中给了提示矩阵。

网赛时才接触矩阵幂运算,自己掌握的知识还是太少了。。。。

代码:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn=2;
const int mod=10000;
int n=2;//矩阵大小
int num;//幂大小

struct mat
{
    int arr[maxn][maxn];
    mat()
    {
        memset(arr,0,sizeof(arr));
    }
};

mat mul(mat a,mat b)
{
    mat ans;
    for(int i=0;i<n;i++)
    {
        for(int k=0;k<n;k++)
        {
            if(a.arr[i][k])
                for(int j=0;j<n;j++)
            {
                ans.arr[i][j]+=a.arr[i][k]*b.arr[k][j];
                if(ans.arr[i][j]>=mod)
                    ans.arr[i][j]%=mod;
            }
        }
    }
    return ans;
}

mat power(mat p,int k)
{
    if(k==1) return p;
    mat e;
    for(int i=0;i<n;i++)
        e.arr[i][i]=1;
    if(k==0) return e;
    while(k)
    {
        if(k&1)
            e=mul(e,p);
        p=mul(p,p);
        k>>=1;
    }
    return e;
}

int main()
{
    mat ori;//题目中的原始矩阵
    ori.arr[0][0]=ori.arr[0][1]=ori.arr[1][0]=1;
    while(cin>>num&&num!=-1)
    {
        mat ans;
        ans=power(ori,num);
        cout<<ans.arr[0][1]<<endl;
    }
    return 0;
}


[ACM] POJ 3070 Fibonacci (矩阵幂运算)