【序言】惊奇的发现,矩阵乘法真是个优化程序的好东西。像矩阵乘法啊、堆啊,我会陆续学习。
【介绍】矩阵乘法:设A矩阵大小m*p,b矩阵大小为p*n,且C=A*B,那么C矩阵大小为m*n。C数组中的c[i][j]表示A矩阵的第i行和b矩阵的第j列两两相乘的和。矩阵具有结合律,但不具有交换律。
【例题*poj3070】
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8345 | Accepted: 5935 |
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
【分析】矩阵乘法重在推递推式。由于初学,我只会做这种简单的题目。刚开始自己是这么推的。设A矩阵是1*2,元素是(a,b),B矩阵是2*2,元素是(0,1,1,1),这样我们可以计算出,A*B=(b,a+b)。这就起到了递推的效果。可以想象,再乘一个B,结果就是(a+b,a+2b)。这就是一个迭代。
然而编完后,我发现我的程序有点问题。我是先算B^n(用快速幂),再算与A的积。但是因为矩阵不具有交换律,所以得到的结果可能有问题。这是我才惊奇的发现,题目上有递推式!然后套用一下,A了。
【原代码(有bug)】
#include<stdio.h>
using namespace std;
const int mo=10000;
struct arr{int v[3][3];}a,b;
int n;
arr chen(arr x,arr y,int m,int n,int p)
{
arr s;
for (int i=1;i<=m;i++)
for (int j=1;j<=p;j++)
{
s.v[i][j]=0;
for (int k=1;k<=n;k++)
s.v[i][j]=(s.v[i][j]+x.v[i][k]*y.v[k][j]%mo)%mo;
}
return s;
}
void quick()
{
int mi=n-1;arr res=b;
while (mi>0)
{
if (mi&1) res=chen(res,b,2,2,2);
b=chen(b,b,2,2,2);
mi/=2;
}
a=chen(a,res,1,2,2);
}
int main()
{
while (scanf("%ld",&n)>-1)
{
if (n==0) {printf("0\n");continue;}
a.v[1][1]=1;a.v[2][1]=1;
b.v[1][1]=0;b.v[1][2]=1;b.v[2][1]=1;b.v[2][2]=1;
quick();
printf("%ld",a.v[1][1]);
}
return 0;
}
【AC代码】
#include<stdio.h>
using namespace std;
const int mo=10000;
struct arr{int v[3][3];}a,b;
int n;
arr chen(arr x,arr y)
{
arr s;int m=2,n=2,p=2;
for (int i=1;i<=m;i++)
for (int j=1;j<=p;j++)
{
s.v[i][j]=0;
for (int k=1;k<=n;k++)
s.v[i][j]=(s.v[i][j]+x.v[i][k]*y.v[k][j]%mo)%mo;
}
return s;
}
void quick()
{
int mi=n-2;a=b;
while (mi>0)
{
if (mi&1) a=chen(a,b);
b=chen(b,b);
mi/=2;
}
}
int main()
{
while (scanf("%ld",&n)>-1)
{
if (n==0) {printf("0\n");continue;}
b.v[1][1]=1;b.v[1][2]=1;b.v[2][1]=1;b.v[2][2]=0;
quick();
printf("%ld\n",a.v[1][1]);
}
return 0;
}