UVA 10698 Yet another Number Sequence 矩阵快速幂

本文介绍了一种利用矩阵快速幂算法高效求解类似斐波那契数列的问题,并考虑了取模运算,适用于解决大数值下数列求值问题。通过具体的C++实现代码展示了算法细节。

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

题意:类似于fibonacci数列的求法,值得注意的是题目并不是让求简单的F(n),而是求f(n)的模

直接矩阵快速幂就可以,顺便求模即可

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define rep(i, j, k) for(int i = j; i <= k; i++)

using namespace std;

const int N = 2;
int MOD = 1;

struct Matrix
{
	int ary[N][N];
	Matrix() {
		memset (ary, 0, sizeof (ary));
	}
};

const Matrix operator*(const Matrix & A, const Matrix & B) 
{
	Matrix t;
	rep (i, 0, N - 1)
		rep (j, 0, N - 1)
			rep (k, 0, N - 1)
				t.ary[i][j] += A.ary[i][k] * B.ary[k][j], t.ary[i][j] %= MOD;
	return t;
}

int quick_pow(int a, int b, int n) 
{
	if (n == 0) return a % MOD;
	if (n == 1) return b % MOD;
	Matrix ans, tmp;
	tmp.ary[0][0] = 1;
	ans.ary[0][0] = (a + b) % MOD;
	rep (i, 0, N - 1)
		tmp.ary[i][1 - i] = 1, ans.ary[i][1 - i] = b % MOD;
	n -= 2;
	while (n)
	{
		if (n & 1)
			ans = ans * tmp;
		n >>= 1;
		tmp = tmp * tmp;
	}
	return ans.ary[0][0];
}

int a, b, n, m;

int main() 
{
	int ti;
	cin >> ti;
	while (ti--)
	{
		scanf("%d%d%d%d", &a, &b, &n, &m);
		MOD = 1;
		while (m--) MOD *= 10;
		printf("%d\n", quick_pow(a, b, n));
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值