poj 3070 矩阵快速幂

POJ 3070



题解: 矩阵快速幂。 转载一篇文章:关于快速幂和矩阵快速幂


code:

/*
adrui's submission 
Language : C++
Result : Accepted
Love : ll
favorite : Dragon Balls

Standing in the Hall of Fame
*/



#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

#define debug 0
#define LL long long
#define mod 10000
#define M(a, b) memset(a, b, sizeof(a))

struct Matrix {
	LL a[2][2];
	void init1() {
		a[0][0] = a[0][1] = a[1][0] = 1;
		a[1][1] = 0;
	}

	void init2() {
		a[0][0] = a[1][1] = 1;
		a[0][1] = a[1][0] = 0;
	}
};

Matrix operator * (Matrix x, Matrix y) {					//矩阵乘法
	Matrix c;
	M(c.a, 0);

	for (int i = 0; i < 2; i++)
		for (int j = 0; j < 2; j++) {
			for (int k = 0; k < 2; k++) {
				c.a[i][j] += (x.a[i][k] * y.a[k][j]) % mod;
			}
			c.a[i][j] %= mod;								//取模
		}

	return c; 
}

Matrix Matrix_fast_mod(Matrix tmp, int b) {

	Matrix c;
	c.init1();												//幂底数矩阵
	while (b) {
		if (b & 1) tmp = tmp * c;							//快速幂
		c = c * c;
		b >>= 1;
	}

	return tmp;
}
LL n;

int main() {
#if debug
	freopen("in.txt", "r", stdin);
#endif //debug
	while (~scanf("%I64d", &n), n != -1) {
		Matrix ans;
		ans.init2();											//初始化一个单位矩阵
		ans = Matrix_fast_mod(ans, n);							//矩阵快速幂
		printf("%I64d\n", ans.a[0][1]);							//根据矩阵输出Fn
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值