您的位置:首页 > 其它

【POJ】3070 - Fibonacci(矩阵快速幂)

2016-07-28 20:52 381 查看
点击打开题目

Fibonacci

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12951 Accepted: 9210
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 <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define MOD 10000
struct Matrix
{
__int64 a[4][4]; //矩阵
int h,w; //行、列
}pr,ans;
void init() //初始化矩阵
{
ans.a[2][1] = ans.a[1][2] = 0;
ans.h = ans.w = 2;
for (int i = 1 ; i <= 2 ; i++) //初始化单位矩阵
ans.a[i][i] = 1;
pr.a[1][1] = pr.a[1][2] = pr.a[2][1] = 1; //初始化初始矩阵
pr.a[2][2] = 0;
pr.w = 2;
pr.h = 2;
}
Matrix Matrix_multiply(Matrix x , Matrix y) //矩阵乘法
{
Matrix t;
CLR(t.a,0);
t.h = x.h; //新矩阵的行数为x的行数
t.w = y.w; //新矩阵的列数为y的列数
for (int i = 1 ; i <= x.h ; i++)
{
for (int j = 1 ; j <= x.w ; j++)
{
if (x.a[i][j] == 0)
continue;
for (int k = 1 ; k <= y.w ; k++)
t.a[i][k] = (t.a[i][k] + x.a[i][j] * y.a[j][k] % MOD) % MOD;
}
}
return t;
}
void Matrix_mod(int n) //矩阵快速幂
{
while (n)
{
if (n & 1)
ans = Matrix_multiply(pr , ans);
pr = Matrix_multiply(pr , pr);
n >>= 1;
}
}
int main()
{
int n;
while (~scanf ("%d",&n) && n != -1)
{
init();
Matrix_mod(n);
printf ("%I64d\n",ans.a[1][2] % MOD);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: