矩阵算法模板

#include <iostream>

#include <algorithm>

using namespace std;

const int MAX = 32;



int n, MOD;



struct Matrix{

	int v[MAX][MAX];

}



Matrix mtAdd(Matrix A, Matrix B){

	Matrix C;

	for(int i = 0; i < n; ++i)

		for(int j = 0; j < n; ++j){

			C.v[i][j] = A.v[i][j] + B.v[i][j];

		}

	return C;

}



Matrix mtMul(Matrix A, Matrix B){

	Matrix C;

	for(int i = 0; i < n; ++i)

 		for(int j = 0; j < n; ++j){

		 	C.v[i][j] = 0;

		 	for(int k = 0; k < n; ++k)

		 	{

	 			C.v[i][j] = (A.v[i][k] * B.v[k][j] + C.v[i][j]) % MOD;

	 		}

		 }

 	return C;

}



Matrix mtPow(Matrix A, int k){

	if(k == 0){

		memset(A.v, 0, sizeof(A.v))v;

		for(int i = 0; i < n; ++i){

			A.v[i][i] = 1;

		}

		return A;

	}

	if(k == 1) return A;

	Matrix C = mtPow(A, k/2);

	if(k & 1) return mtMul(mtMul(C, C), A);

	else return mtMul(C, C);

	return C;	

}



void mtPrint(Matrix A){

	for(int i = 0; i < n; ++i){

		for(int j = 0; j < n; ++j){

			cout << A.v[i][j] <<' ';

		}

		cout << endl;

	}

}


你可能感兴趣的:(算法)