zoukankan      html  css  js  c++  java
  • 模板——矩阵快速幂

    /************************************************
    Author        :powatr
    Created Time  :2015-8-5 21:06:30
    File Name     :b.cpp
    ************************************************/
    
    #include <cstdio>
    #include <algorithm>
    #include <iostream>
    #include <sstream>
    #include <cstring>
    #include <cmath>
    #include <string>
    #include <vector>
    #include <queue>
    #include <deque>
    #include <stack>
    #include <list>
    #include <map>
    #include <set>
    #include <bitset>
    #include <cstdlib>
    #include <ctime>
    using namespace std;
    
    #define lson l, mid, rt << 1
    #define rson mid + 1, r, rt << 1 | 1
    typedef long long ll;
    const int MAX = 50;//矩阵大小
    int n;
    const int INF = 0x3f3f3f3f;
    const int mod = 1e9 + 7;
    
    struct Matrix
    {
        int a[MAX][MAX];
        void inti()
        {
            memset(a, 0, sizeof(a));
            for(int i = 0 ; i < n; i++)
                a[i][i] = 1;
        }
    }matrix;
    
    Matrix mul(Matrix a, Matrix b)//矩阵乘法
    {
        Matrix ans;
        for(int i = 0 ; i < n; i++)
            for(int j = 0 ; j <n ;j++){
                ans.a[i][j] = 0;
                for(int k = 0; k < n; k++){
            if(a.a[i][k] == 0 || b.a[k][j] == 0) continue; ans.a[i][j] += a.a[i][k] * b.a[k][j]; ans.a[i][j] %= mod;
    } } return ans; } Matrix add(Matrix a, Matrix b) //矩阵加法 { int i, j, k; Matrix ans; for(int i = 0 ; i < n; i++) for(int j = 0 ; j < n; j++){ ans.a[i][j] = a.a[i][j] + b.a[i][j]; ans.a[i][j] %= mod; } return ans; } Matrix pow(Matrix a, int n) // 矩阵快速幂 { Matrix ans; ans.inti(); while(n){ if(n&1) ans = mul(ans, a); n>>= 1; a = mul(a, a); } return ans; } Matrix sum(Matrix a, int n)//矩阵幂和 { int m; Matrix ans, pre; if(n == 1) return a; m = n >> 1; pre = sum(a, m); ans = add(pre, mul(pre, pow(a, m))); if(n&1) ans = add(ans, pow(a, n)); return ans; } void output(Matrix a) //输出 { for(int i = 0 ; i < n; i++) for(int j = 0 ; j < n ; j++) printf("%d%c",a.a[i][j], j == n -1 ? ' ' : ' '); } int main() { Matrix ans; scanf("%d", &n); for(int i = 0 ; i < n; i++) for(int j = 0; j < n; j++){ scanf("%d%d", &matrix.a[i][j]); matrix.a[i][j] %= mod; } return 0; }

      

  • 相关阅读:
    睿象云-智能运维平台
    leetcode-----53. 最大子序和
    leetcode-----50. Pow(x, n)
    leetcode-----49. 字母异位词分组
    leetcode-----48. 旋转图像
    leetcode-----47. 全排列 II
    leetcode-----46. 全排列
    leetcode-----44. 通配符匹配
    SpringMVC @RequestParam和@RequestBody的区别
    SpringMVC 接受页面传递参数
  • 原文地址:https://www.cnblogs.com/zero-begin/p/4705871.html
Copyright © 2011-2022 走看看