矩阵乘法模板

#include <stdio.h>
#include <string.h>
typedef long long LL;
const int MAXN = 100 + 5;
const LL mod = 10000007;

struct Mat
{
    LL mat[MAXN][MAXN];
}A, E; // 题目矩阵和单位矩阵

int n;

void Unit(Mat a)
{
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            a.mat[i][j] = (i == j);
}

Mat operator*(Mat a, Mat b)
{
    Mat c;
    memset(c.mat, 0, sizeof(Mat));
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            for(int k = 0; k < n; k++)
            {
                if(a.mat[i][k] && b.mat[k][j])
                {
                    c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * b.mat[k][j]);
                    if(c.mat[i][j] >= mod)
                        c.mat[i][j] %= mod;
                } 
            }
        }
    }   
    return c;
}

Mat operator+(Mat a, Mat b)
{
    Mat c;
    memset(c.mat, 0, sizeof(Mat));
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            c.mat[i][j] = a.mat[i][j] + b.mat[i][j];
            if(c.mat[i][j] >= mod)
                c.mat[i][j] -= mod;
        }
    }
    return c;
}

Mat operator^(Mat A, int x)
{
    Mat c;
    Unit(c);  // 初始化为单位矩阵
    for(; x; x >>= 1)
    {
        if(x & 1)
            c = c * A;
        A = A * A;
    }
    return c;
}

Mat sum(int x)
{
    if(x == 1)
        return A;
    if(x & 1)
        return (A^x) + sum(x-1);
    else
        return sum(x / 2) * ((A^(x/2))+E);
}

 

posted @ 2013-07-27 15:52  芒果布丁  阅读(304)  评论(0编辑  收藏  举报