码迷,mamicode.com
首页 > 其他好文 > 详细

模板——矩阵快速幂

时间:2015-08-05 22:02:55      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

/************************************************
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++)
                ans.a[i][j] += a.a[i][j] * 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;
}

  

模板——矩阵快速幂

标签:

原文地址:http://www.cnblogs.com/zero-begin/p/4705871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!