模板——矩阵快速幂

/************************************************
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 ? '\n' : ' '); } 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; }

  

posted @ 2015-08-05 21:16  Painting、时光  阅读(121)  评论(0编辑  收藏  举报