【矩阵乘法】洛谷P1962 斐波那契数列

版权声明:转载无所谓的。。。 https://blog.csdn.net/xuxiayang/article/details/82662889

链接

https://www.luogu.org/problemnew/show/P1962


大意

求出斐波那契的第 n m o d   1 e 9 + 7


思路

矩阵乘法加速递推
时间复杂度: O ( l o g n × 2 )


代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ymw 1000000007
using namespace std;long long n;
struct node{int a[3][3],r,c;};
inline node mul(node x,node y)//返回x乘y的值
{
    node z;
    memset(&z,0,sizeof(z));
    for(register int i=0;i<x.r;i++)
     for(register int j=0;j<y.c;j++)
      for(register int k=0;k<x.c;k++)
    z.a[i][j]=(z.a[i][j]%ymw+(long long)x.a[i][k]*y.a[k][j]%ymw)%ymw;
    z.r=x.r;z.c=y.c;
    return z;
}
inline int ksm(register long long y)//快速幂
{
    node x,ans;
    memset(&x,0,sizeof(x));
    memset(&ans,0,sizeof(ans));
    x.r=x.c=ans.c=2;
    ans.r=1;
    x.a[0][0]=x.a[1][0]=x.a[0][1]=1;
    ans.a[0][0]=ans.a[0][1]=1;
    while(y)
    {
        if(y&1) ans=mul(ans,x);
        x=mul(x,x);
        y>>=1;
    }
    return ans.a[0][0]%ymw;
}
signed main()
{
    scanf("%lld",&n);
    if(n<3) return putchar(49)&0;
    printf("%d",ksm(n-2));
}

猜你喜欢

转载自blog.csdn.net/xuxiayang/article/details/82662889
今日推荐