矩阵无限方

本文介绍了一种使用快速幂算法计算矩阵A的x次方的方法。通过将矩阵视为整数进行快速幂运算,实现高效计算。文章提供了完整的C++代码实现,并详细解释了核心函数cf的功能及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:
给出一个矩阵A,求A^x。
思路:
把矩阵当作整数进行快速幂。
代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#define GETMOD %1000000007
#define LL long long
using namespace std;
struct node
{
    int xcnt,ycnt;
    LL a[11][11];
    node()
    {
        memset(a,0,sizeof(a));
    }
};
node cf(node x,node y)
{
    node ans;ans.xcnt=x.xcnt;ans.ycnt=y.ycnt;
    for(int i=1;i<=ans.xcnt;i++)
        for(int j=1;j<=ans.ycnt;j++)
            for(int k=1;k<=x.ycnt;k++)
                ans.a[i][j]=(ans.a[i][j]+x.a[i][k]*y.a[k][j]GETMOD)GETMOD;
    return ans;
}
int main()
{
    int n;LL m;node pre;
    scanf("%d%lld",&n,&m);pre.xcnt=n;pre.ycnt=n;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            scanf("%lld",&pre.a[i][j]);
    node ans;ans.xcnt=n;ans.ycnt=n;
    for(int i=1;i<=n;i++)
        ans.a[i][i]=1;
    while(m>0)
    {
        if(m%2==1)ans=cf(pre,ans);
        pre=cf(pre,pre);
        m/=2;
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
            printf("%lld ",ans.a[i][j]);
        printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值