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

    #include <cstdio>
    #include <iostream>
    
    using namespace std;
    
    const int MOD = 10000;
    
    struct matrix
    {
        int m[2][2];
    }ans, base;
    
    matrix multi(matrix a, matrix b)
    {
        matrix tmp;
        for(int i = 0; i < 2; ++i)
        {
            for(int j = 0; j < 2; ++j)
            {
                tmp.m[i][j] = 0;
                for(int k = 0; k < 2; ++k)
                    tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
            }
        }
        return tmp;
    }
    int fast_mod(int n)  // 求矩阵 base 的  n 次幂 
    {
        base.m[0][0] = base.m[0][1] = base.m[1][0] = 1;
        base.m[1][1] = 0;
        ans.m[0][0] = ans.m[1][1] = 1;  // ans 初始化为单位矩阵 
        ans.m[0][1] = ans.m[1][0] = 0;
        while(n)
        {
            if(n & 1)  //实现 ans *= t; 其中要先把 ans赋值给 tmp,然后用 ans = tmp * t 
            {
                ans = multi(ans, base);
            }
            base = multi(base, base);
            n >>= 1;
        }
        return ans.m[0][1];
    }
    
    int main()
    {
        int n;
        while(scanf("%d", &n) && n != -1)
        {   
            printf("%d
    ", fast_mod(n));
        }
        return 0;
    }

    再来一个:

    struct matrix
    {
        int n,m;LL a[22][22];
        matrix operator *(const matrix b)
        {
            matrix c;c.n=n;c.m=b.m;
            memset(c.a,0,sizeof(c.a));
            for(int i=1;i<=c.n;i++)
                for(int j=1;j<=c.m;j++)
                for(int k=1;k<=m;k++)
                c.a[i][j]+=a[i][k]*b.a[k][j];
            return c;
        }
    }ma,mb;

    其实就是快速幂的原理!

  • 相关阅读:
    MySQL锁概述
    MYSQL删除重复记录
    SPRING事务控制
    性能测试中如何确定并发用户数
    Jsoup操作
    linux根据端口号查询进程
    linux下解压jar文件
    开发阶段的logback.xml
    栈--getMin(leetcode 155)
    git "fatal: The remote end hung up unexpectedly"
  • 原文地址:https://www.cnblogs.com/weeping/p/5690247.html
Copyright © 2011-2022 走看看