zoukankan      html  css  js  c++  java
  • luogu P3390 【模板】矩阵快速幂

    题目背景

    矩阵快速幂

    题目描述

    给定n*n的矩阵A,求A^k

    输入输出格式

    输入格式:

    第一行,n,k

    第2至n+1行,每行n个数,第i+1行第j个数表示矩阵第i行第j列的元素

    输出格式:

    输出A^k

    共n行,每行n个数,第i行第j个数表示矩阵第i行第j列的元素,每个元素模10^9+7

    输入输出样例

    输入样例#1:

    2 1
    1 1
    1 1

    输出样例#1:

    1 1
    1 1
    说明

    n<=100, k<=10^12, |矩阵元素|<=1000 算法:矩阵快速幂

    如题

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    #define LL long long
    int n;LL k;
    const int mod = 1e9+7;
    struct Matrix {
        LL a[107][107];
        Matrix() {
            std::memset(a,0,sizeof a);
        }
        Matrix operator * (const Matrix & y)const   {
            Matrix ans;
            for(int i=1;i<=n;++i) {
                for(int j=1;j<=n;++j) {
                    for(int k=1;k<=n;++k) {
                        ans.a[i][j]=(ans.a[i][j]+((a[i][k]%mod)*(y.a[k][j]%mod)))%mod;
                    }
                }
            }
            return ans;
        }
            
    }pre,ans;
    void pow(LL k) {
        for(int i=1;i<=n;++i) 
            ans.a[i][i]=1;
        while(k) {
            if(k&1) ans=ans*pre;
            pre=pre*pre;
            k>>=1;
        }
        for(int i=1;i<=n;++i) {
            for(int j=1;j<=n;++j) {
                printf("%lld ",ans.a[i][j]);
            }
            puts("");
        }
        return ;
    }
    int main() {
        scanf("%d%lld",&n,&k);
        for(int i=1;i<=n;++i) {
            for(int j=1;j<=n;++j) {
                scanf("%d",&pre.a[i][j]);
            }
        }
        pow(k);
        return 0;
    }
    
  • 相关阅读:
    获取全部校园新闻
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    团队总结
    团队第二阶段冲刺绩效评估
    第二阶段冲刺第七天站立会议
    第二阶段冲刺第六天站立会议
    第二阶段冲刺第五天站立会议
    内测版本
    第二阶段冲刺第四天站立会议
  • 原文地址:https://www.cnblogs.com/sssy/p/7799891.html
Copyright © 2011-2022 走看看