codeforces 185A Plant

來源:互聯網
上載者:User

點擊開啟cf 185A

思路: 遞推+矩陣快速冪

分析:

1 題目要求找到在n年後向上三角形的個數

2 寫出前面的幾個數F(0) = 1 , F(1) = 3 , F(2) = 10 , F(3) = 36 , F(4) = 136

   通過前面幾項我們可以找到通項公式F[n] = 4*F[n-1]-2^(n-1)

     那麼我們通過夠找矩陣

   | 4 -1 |  *  | F(n-1) | = | F(n) |

   | 0 2 |      | 2^(n-1) |   | 2^n |

3 那麼夠造出矩陣之後我們直接利用矩陣快速冪,由於矩陣開始有負數,所以應該在模數的時候注意一下


代碼:

/************************************************ * By: chenguolin                               *  * Date: 2013-08-23                             * * Address: http://blog.csdn.net/chenguolinblog * ***********************************************/#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef __int64 int64;const int MOD = 1e9+7;const int N = 2;int64 n;struct Matrix{    int64 mat[N][N];    Matrix operator*(const Matrix& m)const{        Matrix tmp;        for(int i = 0 ; i < N ; i++){            for(int j = 0 ; j < N ; j++){                tmp.mat[i][j] = 0;                for(int k = 0 ; k < N ; k++){                    tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%MOD;                    tmp.mat[i][j] %= MOD;                }            }        }        return tmp;    }};int64 Pow(Matrix &m){    if(n == 0)        return 1;    Matrix ans;    ans.mat[0][0] = 1 , ans.mat[0][1] = 0;    ans.mat[1][0] = 0 , ans.mat[1][1] = 1;    while(n){        if(n%2)            ans = ans*m;        n /= 2;        m = m*m;    }    int64 sum = 0;    sum = (ans.mat[0][0]+ans.mat[0][1])%MOD;    sum = (sum+MOD)%MOD;    return sum;}int main(){    Matrix m;    while(cin>>n){         m.mat[0][0] = 4 , m.mat[0][1] = -1;         m.mat[1][0] = 0 , m.mat[1][1] = 2;         cout<<Pow(m)<<endl;    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.