薛磊 Job Seeker

51nod_1113 矩阵快速幂


传送门

Problem Description

给出一个N * N的矩阵,其中的元素均为正整数。求这个矩阵的M次方。由于M次方的计算结果太大,只需要输出每个元素Mod (10^9 + 7)的结果。

Input

第1行:2个数N和M,中间用空格分隔。N为矩阵的大小,M为M次方。(2 <= N <= 100, 1 <= M <= 10^9)
第2 - N + 1行:每行N个数,对应N * N矩阵中的1行。(0 <= N[i] <= 10^9)

Output

共N行,每行N个数,对应M次方Mod (10^9 + 7)的结果。

Sample Input

2 3
1 1
1 1

Sample Output

4 4
4 4

Solution

矩阵快速幂问题

#include<iostream>
using namespace std;

typedef long long ll;
const int maxn = 110;
const int MOD = 1e9+7;
//宏定义 用来替代一段代码
#define mod(x) ((x)%MOD);
int n;

//矩阵结构体
struct mat{
    int m[maxn][maxn];
}unit;

//乘法重载
mat operator * (mat a,mat b){
    mat ret;
    ll x;
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++){
            x=0;
            for(int k=0;k<n;k++){
                x += mod((ll)a.m[i][k]*b.m[k][j]);
            }
            ret.m[i][j] = mod(x);
        }
    return ret;
}
//单位矩阵初始化
void init_unit(){
    for(int i=0;i<maxn;i++)
        unit.m[i][i] = 1;
        return ;
}
//快速幂
mat pow_mat(mat a,ll n){
    mat ret = unit;
    while(n){
        if(n&1) ret = ret*a;
        a = a*a;
        n>>=1;
    }
    return ret;
}
int main(){
    ll x;
    init_unit();
    while(cin>>n>>x){
        mat a;
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                cin>>a.m[i][j];
        a = pow_mat(a,x);
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                if(j+1==n) cout<<a.m[i][j]<<endl;
                else cout<<a.m[i][j]<<" ";
    }
    return 0;
}

Comments

Content