【BZOJ2326】[HNOI2011]数学作业【矩阵快速幂】

本文介绍了一种利用矩阵快速幂进行分段计算的方法,并通过具体实现展示了如何针对不同区间进行高效运算。此方法适用于解决特定类型的问题,尤其是在数学算法和编程竞赛中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目链接】

原来矩阵快速幂还可以分段玩。

/* Telekinetic Forest Guard */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

LL n;
int p; 

struct mat {
	int num[3][3];
} E, ans;

inline LL mul(LL a, LL b) {
	return a * b % p;
}

inline mat matmul(mat A, mat B) {
	mat res;
	for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) {
		res.num[i][j] = 0;
		for(int k = 0; k < 3; k++) (res.num[i][j] += mul(A.num[i][k], B.num[k][j])) %= p;
	}
	return res;
}

inline void calc(LL k, LL n) {
	mat trans;
	trans.num[0][0] = k; trans.num[0][1] = 0; trans.num[0][2] = 0;
	trans.num[1][0] = 1; trans.num[1][1] = 1; trans.num[1][2] = 0;
	trans.num[2][0] = 1; trans.num[2][1] = 1; trans.num[2][2] = 1;
	mat res = E;
	for(; n; n >>= 1, trans = matmul(trans, trans)) if(n & 1) res = matmul(res, trans);
	ans = matmul(ans, res);
}

int main() {
	scanf("%lld%d", &n, &p);

	for(int i = 0; i < 3; i++) E.num[i][i] = 1;
	ans = E;

	LL cnt = 10;
	for(; cnt <= n; cnt *= 10) calc(cnt % p, cnt - cnt / 10);
	calc(cnt % p, n - cnt / 10 + 1);

	printf("%d\n", ans.num[2][0]);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值