【序言】驚奇的發現,矩陣乘法真是個優化程序的好東西。像矩陣乘法啊、堆啊,我會陸續學習。
【介紹】矩陣乘法:設A矩陣大小m*p,b矩陣大小為p*n,且C=A*B,那麼C矩陣大小為m*n。C數組中的c[i][j]表示A矩陣的第i行和b矩陣的第j列兩兩相乘的和。矩陣具有結合律,但不具有交換律。
【例題*poj3070】
Fibonacci Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8345 Accepted: 5935Description
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
.<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+R2l2ZW4gYW4gaW50ZWdlciA8ZW0+bjwvZW0+LCB5b3VyIGdvYWwgaXMgdG8gY29tcHV0ZSB0aGUgbGFzdCA0IGRpZ2l0cyBvZiA8ZW0+RjxzdWI+bjwvc3ViPjwvZW0+LjwvcD4KCjxwIGNsYXNzPQ=="pst">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【分析】矩陣乘法重在推遞推式。由於初學,我只會做這種簡單的題目。剛開始自己是這麼推的。設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)】
#includeusing 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; }
#includeusing 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; }