• 51nod 矩阵快速幂(模板题)


    基准时间限制:3 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
    给出一个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)的结果。
    Input示例
    2 3
    1 1
    1 1
    Output示例
    4 4
    4 4

    思路:矩阵快速幂模板,写的不好的地方就请大家见谅了

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstring>
     4 #include<cmath>
     5 using namespace std;
     6 typedef long long LL;
     7 const int N = 105;
     8 const LL mod = 1e9 + 7;
     9 LL n, m;
    10 struct mac {
    11     LL c[N][N];
    12     void reset() {
    13         memset(c, 0, sizeof(c));
    14         for (int i = 1; i <= n; i++)
    15             c[i][i] = 1;
    16     }
    17 };
    18 mac multi(mac a, mac b) 
    19 {
    20     mac ans;
    21     for (int i = 1; i <= n; i++)
    22         for (int j = 1; j <= n; j++) {
    23             ans.c[i][j] = 0;
    24             for (int k = 1; k <= n; k++) {
    25                 ans.c[i][j] += (a.c[i][k] * b.c[k][j]) % mod;
    26                 ans.c[i][j] %= mod;
    27             }
    28         }
    29     return ans;
    30 }
    31 mac Pow(mac a, LL b) 
    32 {
    33     mac ans; ans.reset();
    34     while (b) {
    35         if (b & 1) 
    36             ans = multi(ans, a);
    37         a = multi(a, a);
    38         b >>= 1;
    39     }
    40     return ans;
    41 }
    42 int main()
    43 {
    44     ios::sync_with_stdio(false);
    45     while (cin >> n >> m) {
    46         mac a;
    47         for (int i = 1; i <= n; i++)
    48             for (int j = 1; j <= n; j++)
    49                 cin >> a.c[i][j];
    50         a = Pow(a, m);
    51         for (int i = 1; i <= n; i++) {
    52             for (int j = 1; j < n; j++)
    53                 cout << a.c[i][j] << " ";
    54             cout << a.c[i][n] << endl;
    55         }
    56     }
    57     return 0;
    58 }
  • 相关阅读:
    零拷贝报文捕获平台
    Table of Contents ---BCM
    bcm cmd
    Linux常用性能调优工具索引
    Vue params传值的坑
    安装了新的angular版本后无法运行老的angular版本项目
    后端返回的数据与前端console.log数据不一致问题
    门户页跳转页面 跳转指定的页面 接口会变成路由去显示 而不是显示组件
    配置git ssh 密钥
    grafana环境变量
  • 原文地址:https://www.cnblogs.com/wangrunhu/p/9447193.html
Copyright © 2020-2023  润新知