【模板】矩阵快速幂

#include <stdio.h>
#include <string.h>
int moyn = 998244353;
template<typename Tec,int __a>
struct MATRIX {
	Tec mat[__a][__a];
	MATRIX () {memset(mat,0,sizeof(mat));}
	MATRIX (int type) {
		if(type == 1) {
			memset(mat,0,sizeof(mat));
			for(int i = 0;i < __a;++i) 
				mat[i][i] = 1;
		} else if(type == 2) {
			mat[0][0] = mat[1][0] = mat[0][1] = 1;
		}
	}
	MATRIX operator * (const MATRIX &__in) const {
		MATRIX res;
		Tec tmp;
		for(int i = 0;i < __a;++i) 
			for(int k = 0;k < __a;++k) {
				tmp = mat[i][k];
				for(int j = 0;j < __a;++j) 
					res.mat[i][j] = (res.mat[i][j]+tmp*__in.mat[k][j])%moyn;
			}
		return res;
	}
	MATRIX operator ^ (int __n) const {
		MATRIX res(1);
		MATRIX _a = *this;
		while(__n) {
			if(__n&1) 
				res = res*_a;
			_a = _a*_a;
			__n >>= 1;
		}
		return res;
	}
};
MATRIX<long long,2> a(2);
MATRIX<long long,3> b;
int n;
signed main() {
	a.mat[0][0] = a.mat[0][1] = a.mat[1][0] = 1;
	scanf("%d",&n);
	a = a^(n-1);
	printf("%lld",a.mat[0][0]);
}

posted @ 2022-02-17 14:50  bikuhiku  阅读(24)  评论(0编辑  收藏  举报