poj 3070 -- Fibonacci

Posted studyshare777

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 3070 -- Fibonacci相关的知识,希望对你有一定的参考价值。

http://poj.org/problem?id=3070

Language:
Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25706   Accepted: 17173

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:

技术图片.

::矩阵快速幂模板题,已经给出了转移矩阵T。

记录下自己写的模板。

学习的博客:https://blog.csdn.net/zhangxiaoduoduo/article/details/81807338

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<sstream>
#include<vector>
#include<stack>
#include<deque>
#include<cmath>
#include<map>
#define sd(x) scanf("%d",&x)
#define ms(x) memset(x,0,sizeof x)
#define fr(i,n) for(int i=1;i<=n;i++)
using namespace std;
typedef long long ll;
const int mod=10000;
const int INF=0x4f4f4f3f;
ll t[3][3],tmp[3][3],res[3][3]; 
ll f[3][3];
void multi(ll (&a)[3][3],ll b[][3])
{
    ms(tmp);
    for(int i=0;i<2;i++)
    for(int k=0;k<2;k++)
    for(int j=0;j<2;j++)
    tmp[i][j]+=(a[i][k]*b[k][j])%mod;
    for(int i=0;i<2;i++)
    for(int j=0;j<2;j++)
    a[i][j]=tmp[i][j]%mod;
}
/*
void pr()
{
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        printf("%d ",t[i][j]);
        cout<<‘
‘;
     } 
}
*/
void mp(ll (&t)[3][3],ll n)
{
    ms(res);
    res[0][0]=res[1][1]=1;
    while(n)
    {
        //pr();
        if(n&1) multi(res,t);
        multi(t,t);
        n>>=1;
    }
}
void init()
{
    ms(f);
    f[0][0]=1;
    ms(t);
    t[0][0]=t[1][0]=t[0][1]=1;
}
int main()
{
    while(1)
    {
        ll n;
        cin>>n;
        if(n==-1) break;
        if(n==0||n==1) 
        {
            printf("%lld
",n);
            continue;
        }
        init();
        mp(t,n-1);
        multi(res,f);
        printf("%lld
",res[0][0]%mod);
    }
    return 0;
}

 

以上是关于poj 3070 -- Fibonacci的主要内容,如果未能解决你的问题,请参考以下文章

POJ 3070 Fibonacci

poj 3070 -- Fibonacci

POJ 3070 Fibonacci

poj 3070 -- Fibonacci

poj3070Fibonacci 矩阵快速幂

[POJ] 3070 Fibonacci