1. 程式人生 > >遞推式計算與矩陣乘法 C++

遞推式計算與矩陣乘法 C++

以斐波那契數列為例,計算斐波那契數列的矩陣方法程式碼如下:

(快速冪、矩陣乘法)《挑戰程式設計競賽第二版》P199

#include<iostream>
#include<vector>
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
int M = 10000;
mat mul(mat &A,mat &B){
	mat C(A.size(),vec(B[0].size()));
	for(int i = 0;i < A.size();i++)
		for(int k = 0;k < B.size();k++)
			for(int j = 0;j < B[0].size();j++)
				C[i][j] = (C[i][j] + A[i][k]*B[k][j])%M;
	return C;
}
mat pow(mat A,int n){
	mat res(A.size(),vec(A.size()));
	for(int i = 0;i < A.size();i++)	res[i][i] = 1;
	while(n > 0){
		if(n & 1)	res = mul(res,A);
		A = mul(A,A);
		n >>= 1;
	}
	return res;
}
void print(mat &A){
	for(int i = 0;i < A.size();i++){
		for(int j = 0;j < A[0].size();j++)
			cout << A[i][j] << " ";
		cout << endl;
	}
} 
int main()
{
	mat A(2,vec(2));
	A[0][0] = A[0][1] = A[1][0] = 1;
	A[1][1] = 0;
	print(A);	
	A = pow(A,100);
	print(A);
	return 0;
}