矩阵快速幂 模板

结构体+重载运算符写法

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
#define LL long long 
using namespace std;
const int MOD=1e9+7;
LL init(){
	LL rv=0,fh=1;
	char c=getchar();
	while(c<'0'||c>'9'){
		if(c=='-') fh=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9'){
		rv=(rv<<1)+(rv<<3)+c-'0';
		c=getchar();
	}
	return rv*fh;
}
LL k,n;
struct matrix{
	LL num[105][105];
	matrix(){
		memset(num,0,sizeof(num));
	}
	void qread(){
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				num[i][j]=init();
			}
		}
	}
	matrix operator * (const matrix &b) const{
		matrix res,a=(*this);
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				res.num[i][j]=0;
				for(int k=1;k<=n;k++){
					(res.num[i][j]+=a.num[i][k]*b.num[k][j])%=MOD;
				}
			}
		}
		return res;	
	}
	void print(){
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				printf("%d ",num[i][j]);
			}
			printf("\n");
		}
	}
	matrix operator ^ (LL k){
		matrix res,b=(*this);
		for(int i=1;i<=n;i++){
			res.num[i][i]=1;
		}
		while(k){
			if(k&(LL)1) res=res*b;
			b=b*b;
			k>>=1;
		}
		return res;
	}
}jz;
int main(){
	freopen("in.txt","r",stdin);
	n=init(),k=init();
	jz.qread();
	jz=jz^k;
	jz.print();
	fclose(stdin);
	return 0;
}

十个可以用矩阵快速幂解决的经典题目

posted @ 2017-12-18 11:01  Mr_Wolfram  阅读(163)  评论(1编辑  收藏  举报