Matrix Power Series 题解

文章讲述了利用矩阵快速幂和分治思想求解矩阵累加和问题,涉及矩阵乘法和等比数列求和技巧。

描述

Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.

输入

The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 10^9) and m (m < 10^4). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.

输出

Output the elements of S modulo m in the same way as A is given.

样例输入

2 2 4
0 1
1 1
 

样例输出

1 2
2 3
 


题意是对一个n*n的矩阵,求上述式子的结果。

一般来说用等比数列求和来计算,但是这里是矩阵没法求1-A和1-A^k,所以用分治的方式去求,其中需要求矩阵的乘方,用矩阵快速幂求解。

类似于一般的快速幂求法,在求矩阵快速幂里的ans数组要先赋值成单位矩阵,其他的和快速幂一样,因为不能直接返回数组,所以这个用一个结构体表示矩阵(一开始形参不小心写了二维数组就错了,救命)。

然后用分治的方式求等比数列的和。令等比数列从1到n的和为f[n],分为两种情况:
        n为奇数:f[n] = f[n >> 1] + a ^ n;

        n为偶数:f[n] = f[n >> 1]

然后递归处理就可以得到答案了

#include<bits/stdc++.h>

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 50;
int MOD;
LL n, m, k;
struct Martix {
	LL a[N][N];
	Martix(){memset(a, 0, sizeof a);}
};

Martix a, ans;
// int h[N], e[N], ne[N], idx;
// void add(int a, int b) {
// 	e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
// }

Martix mul(Martix a, Martix b) {
    Martix c;
    for(int i = 0;i < n;i ++) {
        for(int j = 0;j < n;j ++) {
            for(int k = 0;k < n;k ++)
                c.a[i][j] = (c.a[i][j] + a.a[i][k] * b.a[k][j]) % MOD;
        }
    }

	return c;
}

Martix add(Martix a, Martix b) {
    Martix c;
    for(int i = 0;i < n;i ++) {
        for(int j = 0;j < n;j ++) {
    	   c.a[i][j] = (a.a[i][j] + b.a[i][j]) % MOD;
        }
    }
	return c;
}

Martix ksm(Martix a, LL b) {
	Martix res;
	for(int i = 0;i < n;i ++)
		res.a[i][i] = 1;
	while(b) {
		if(b & 1) res = mul(res, a);
		a = mul(a, a);
		b >>= 1;
	}
	
	return res;
}

Martix solve(int x) {
	if(x == 1) return a;
	Martix t = solve(x >> 1);
	if(x & 1) {
		return add(ksm(a, x), add(t, mul(t, ksm(a, x >> 1))));
	}
	return add(t, mul(t, ksm(a, x >> 1)));
}

int main() { 
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> n >> k >> MOD;
	for(int i = 0;i < n;i ++)
		for(int j = 0;j < n;j ++)
			cin >> a.a[i][j];

	ans = solve(k);
	for(int i = 0;i < n;i ++){
		for(int j = 0;j < n;j ++){
			if(j) cout << ' ';
			cout << ans.a[i][j] % MOD;
		}
		cout << '\n';
	}		
	
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值