博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ 3233 - Matrix Power Series(矩阵快速幂)
阅读量:4596 次
发布时间:2019-06-09

本文共 2355 字,大约阅读时间需要 7 分钟。

Description

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

Input

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

Output

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

Sample Input

2 2 4

0 1
1 1

Sample Output

1 2

2 3


Solution

题目大意:给一个n*n矩阵A 和 系数k, 求 S=A+A2+A3++Ak
定义一个2n*2n的矩阵B,I为单位矩阵

Bn+1=A0IIn+1=An0A+A2+A3+...+An+II
Bn+1B[0][1]I即可。


Code

include 
#include
#include
#include
using namespace std;#define maxn 100typedef long long ll;struct Mat{ int mat[maxn][maxn];//矩阵 int row, col;//矩阵行列数 };Mat mod_mul(Mat a, Mat b, int p)//矩阵乘法 { Mat ans; ans.row = a.row; ans.col = b.col; memset(ans.mat, 0, sizeof(ans.mat)); for (int i = 1;i <= ans.row;i++) for (int j = 1;j <= ans.col;j++) for (int k = 1;k <= a.col;k++) { ans.mat[i][j] += a.mat[i][k] * b.mat[k][j]; ans.mat[i][j] %= p; } return ans;}Mat mod_pow(Mat a, int k, int p)//矩阵快速幂 { Mat ans; ans.row = a.row; ans.col = a.col; for (int i = 1;i <= a.row;i++) for (int j = 1;j <= a.col;j++) ans.mat[i][j] = (i == j); while (k) { if (k & 1)ans = mod_mul(ans, a, p); a = mod_mul(a, a, p); k >>= 1; } return ans;}int main(){ int n, m, k; while (~scanf("%d%d%d", &n, &k, &m)) { Mat A; A.row = A.col = 2 * n; memset(A.mat, 0, sizeof(A.mat)); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) scanf("%d", &A.mat[i][j]); for (int i = 1; i <= n; i++) A.mat[i][i + n] = A.mat[i + n][i + n] = 1;//初始化单位矩阵 Mat B = mod_pow(A, k + 1, m); for (int i = 1; i <= n; i++) for (int j = n+1; j <= 2*n; j++) { if (i + n == j) printf("%d", ((B.mat[i][j] - 1) % m+m)%m);//((B.mat[i][j] - 1) % m+m)%m 避免结果为负数 else printf("%d", B.mat[i][j]); printf("%c", j == 2 * n ? '\n' : ' '); } } return 0;}

转载于:https://www.cnblogs.com/Chizhao/p/10439762.html

你可能感兴趣的文章
Linux常用网站
查看>>
软件开发人员必须具备的20款免费的windows下的工具(转载)
查看>>
MyBatis源码探索
查看>>
python 迭代
查看>>
File查看目录
查看>>
去除ActionBar的方法
查看>>
STM8S——Universal asynchronous receiver transmitter (UART)
查看>>
Flink - state管理
查看>>
Apache Kafka - KIP-42: Add Producer and Consumer Interceptors
查看>>
ArcGIS JS Demo
查看>>
webservice发布问题,部署iis后调用不成功
查看>>
Koch 分形,海岸线,雪花
查看>>
ubuntu系统下Python虚拟环境的安装和使用
查看>>
IOS7开发~新UI学起(二)
查看>>
软件过程度量和CMMI模型概述
查看>>
数据结构(DataStructure)与算法(Algorithm)、STL应用
查看>>
Linux与Windows xp操作系统启动过程
查看>>
linux运维、架构之路-Kubernetes1.13离线集群部署双向认证
查看>>
[Leetcode]Substring with Concatenation of All Words
查看>>
Gem install rmagick 报错问题~
查看>>