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;
    }
    
  • 相关阅读:
    第7章例7-12
    第7章例7-11
    第7章例7-9
    第7章例7-8
    第7章例7-7
    第7章例7-6
    第7章例7-5
    第7章例7-4
    第7章例7-3
    第7章例7-2
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14653419.html
Copyright © 2011-2022 走看看