zoukankan      html  css  js  c++  java
  • 51Nod 1113 矩阵快速幂

    基准时间限制: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

    源代码(感谢Nemaleswang):

     

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 typedef long long ll;
     4 const int maxn=110;
     5 const int MOD=1e9+7;
     6 #define mod(x) ((x)%MOD)
     7 int n;
     8 struct mat {
     9     int m[maxn][maxn];
    10 }unit;
    11 mat operator * (mat a, mat b) {
    12     mat ret;
    13     ll x;
    14     for(int i=0;i<n;++i) {
    15         for(int j=0;j<n;++j) {
    16             x=0;
    17             for(int k=0;k<n;++k) {
    18                 x+=mod((ll)a.m[i][k]*b.m[k][j]);
    19             }
    20             ret.m[i][j]=mod(x);
    21         }
    22     }
    23     return ret;
    24 }
    25 void init_unit() {
    26     for(int i=0;i<maxn;++i)
    27         unit.m[i][i]=1;
    28     return;
    29 }
    30 mat pow_mat(mat a, ll x) {
    31     mat ret=unit;
    32     while(x) {
    33         if(x&1) ret=ret*a;
    34         a=a*a;
    35         x>>=1;
    36     }
    37     return ret;
    38 }
    39 int main() {
    40     ll x;
    41     init_unit();
    42     while(cin>>n>>x) {
    43         mat a;
    44         for(int i=0;i<n;++i)
    45             for(int j=0;j<n;++j)
    46                 cin>>a.m[i][j];
    47         a=pow_mat(a,x);
    48         for(int i=0;i<n;++i) {
    49             for(int j=0;j<n;++j) {
    50                 if(j+1==n) cout<<a.m[i][j]<<endl;
    51                 else cout<<a.m[i][j]<<" ";
    52             }
    53         }
    54     }
    55     return 0;
    56 }
    View Code

     

     

  • 相关阅读:
    linq判断集合是否为空的方法
    MVC控制器取参数值
    linq查询结果转换为指定字段类型的list集合
    C#Web异步操作封装
    js基础细节
    写入临时日志到文本
    css3超过指定宽度文字,显示省略号
    如何判断Javascript对象是否存在
    chrome下input[type=text]的placeholder不垂直居中的问题解决
    sqlserver临时表操作
  • 原文地址:https://www.cnblogs.com/lemonbiscuit/p/7775966.html
Copyright © 2011-2022 走看看