zoukankan      html  css  js  c++  java
  • 1303. 斐波那契前 n 项和

    [f_n = f_{n-1}+f_{n-2} \ S_n=S_{n-1}+f_n \ [f_n,f_{n-1},S_n]= [f_{n-1},f_{n-2},S_{n-1}] egin{bmatrix} 1 & 1 & 1\ 1 & 0 & 1\ 0 & 0 & 1 end{bmatrix} =[f_1,f_0,S_1] egin{bmatrix} 1 & 1 \ 1 & 0 end{bmatrix}^{n-1} ]

    const int N=3;
    int n,mod;
    
    void mul(int f[],int m[][N])
    {
        int c[N]={0};
        for(int i=0;i<N;i++)
            for(int j=0;j<N;j++)
                c[i]=(c[i]+(LL)f[j]*m[j][i])%mod;
        memcpy(f,c,sizeof c);
    }
    
    void mulself(int m[][N])
    {
        int c[N][N]={0};
        for(int i=0;i<N;i++)
            for(int j=0;j<N;j++)
                for(int k=0;k<N;k++)
                    c[i][j]=(c[i][j]+(LL)m[i][k]*m[k][j])%mod;
        memcpy(m,c,sizeof c);
    }
    
    int main()
    {
        int f[N]={1,0,1};
        int m[N][N]={{1,1,1},
                     {1,0,1},
                     {0,0,1}};
    
        cin>>n>>mod;
    
        if(n == 1)
            cout<<f[0]<<endl;
        else
        {
            n--;
            while(n)
            {
                if(n & 1) mul(f,m);
                mulself(m);
                n>>=1;
            }
    
            cout<<f[2]<<endl;
        }
        //system("pause");
        return 0;
    }
    
  • 相关阅读:
    前端面试题
    js collection
    javascript变量声明提升(hoisting)
    css3动画
    神奇的meta
    wap站bug小结
    前端collection
    js拾遗
    prototype之初印象
    自定义scrollBottom的值
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14653419.html
Copyright © 2011-2022 走看看