运算符重载 对象矩阵幂和

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

 




#include <iostream> #include <cstdio> #include <cstring> using namespace std; int m,n,K; int a[30][30]; class Matrix { public: int num[4*30][4*30]; Matrix() { memset(num,0,sizeof(num)); } void print() { for(int i=0;i<n;++i) { printf("%d",num[i][0]); for(int j=1;j<n;++j) printf(" %d",num[i][j]); printf("\n"); } printf("\n"); } friend Matrix& operator *(Matrix max1,Matrix max2); }; Matrix& operator *(Matrix max1,Matrix max2) { Matrix tmp; for(int i=0;i<2*n;++i) for(int j=0;j<2*n;++j) { for(int k=0;k<2*n;++k) tmp.num[i][j]+=(max1.num[i][k]*max2.num[k][j])%m; tmp.num[i][j]%=m; } return tmp; } int main() { scanf("%d %d %d",&n,&K,&m); for(int i=0;i<n;++i) for(int j=0;j<n;++j) scanf("%d",&a[i][j]); Matrix b,c; for(i=0;i<n;++i) for(int j=0;j<n;++j) c.num[i+n][j+n]=b.num[i][j+n]=a[i][j]; for(int k=0;k<2;++k) for(int i=0;i<n;++i) c.num[i+k*n][i]=1; while(K) { if(K&1) b=b*c; K>>=1; c=c*c; } b.print(); return 0; }

 

转载于:https://www.cnblogs.com/huashiyiqike/articles/2860306.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值