51Nod 1113 矩阵快速幂

来源:互联网 发布:headfirst python pdf 编辑:程序博客网 时间:2024/06/06 08:41

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 31 11 1

Sample Output

4 44 4

题解:

矩阵快速幂 用结构体定义的 新技能get

AC代码

#include <bits/stdc++.h>using namespace std;#define ll long longconst int mod = 1e9+7;int n;struct node {    ll arr[100][100];};node mul(node x, node y){    node ans;    memset(ans.arr,0,sizeof(ans.arr));    for(int i = 0;i < n; i++) {        for(int j = 0;j < n; j++) {            for(int k = 0;k < n; k++) {                ans.arr[i][j] = (ans.arr[i][j]+x.arr[i][k]*y.arr[k][j]%mod)%mod;             }           }    }       return ans;}node powMod(ll u, node x){    node ans;    for(int i = 0;i < n; i++) {        for(int j = 0;j < n; j++) {            if(i==j) ans.arr[i][j] = 1;            else ans.arr[i][j] = 0;        }    }    while(u) {        if(u&1) ans = mul(ans,x);        x = mul(x,x);        u>>=1;    }return ans;}int main(){    int m;    node x;    scanf("%d%d",&n,&m);    for(int i = 0;i < n; i++) {        for(int j  = 0; j < n; j++) {            scanf("%lld",&x.arr[i][j]);        }    }    x = powMod(m,x);    for(int i = 0;i < n; i++) {        for(int j = 0;j < n; j++) {            if(j) printf(" ");            printf("%lld",x.arr[i][j]);        }        printf("\n");    }return 0;}
0 0
原创粉丝点击