矩阵快速幂模板+例题

矩阵快速幂这个算法,理解起来很容易,但是我之前自己写的代码有bug,也是因为上课不听课,对形参和实参没理解,平常用的都是全局变量,是不是实参影响不大,这次定义一个结构体的矩阵,矩阵需要初始化为0,然后,因为形参和实参没怎么理解,导致输出的答案差异很大,前提是矩阵快速幂,矩阵需要初始化数组,并不会默认为0

重要的事情讲三遍:

矩阵需要初始化,并不会默认为0!
矩阵需要初始化,并不会默认为0!
矩阵需要初始化,并不会默认为0!

例题:Fibonacci

AC代码:

#include<iostream>
#include<cstring>
using namespace std;
const int mod=1e4;
struct node
{
    int a[2][2];//矩阵
};
void mes(node&d)
{
    for(int i=0; i<2; i++)
    {
        for(int j=0; j<2; j++)
        {
            d.a[i][j]=0;
        }
    }
}
void init(node &res)
{
    mes(res);
    for(int i=0; i<2; i++)
        res.a[i][i]=1;
}
node mul(node b,node c,int mod)
{
    node d;
    mes(d);
    for(int i=0; i<2; i++)
    {
        for(int j=0; j<2; j++)
        {
            for(int k=0; k<2; k++)
            {
                d.a[i][j]=(d.a[i][j]+(b.a[i][k]*c.a[k][j])%mod)%mod;
            }
        }
    }
    return d;
}
node quick(node a,int b)
{
    node res;
    init(res);
    while(b)
    {
        if(b&1)
            res=mul(res,a,mod);
        a=mul(a,a,mod);
        b>>=1;
    }
    return res;
}
int main()
{
    int n;
    while(cin>>n&&(n!=-1))
    {
        node b;
        b.a[0][0]=b.a[0][1]=b.a[1][0]=1;
        b.a[1][1]=0;
        node res=quick(b,n);
        cout<<res.a[0][1]<<endl;
    }
}
发布了222 篇原创文章 · 获赞 16 · 访问量 9739

猜你喜欢

转载自blog.csdn.net/yangzijiangac/article/details/104189626
今日推荐