zoukankan      html  css  js  c++  java
  • codeforces 185A Plant

    点击打开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;
    }
    
    


  • 相关阅读:
    系统优化怎么做-JVM优化之开篇
    系统优化怎么做-Tomcat优化
    系统优化怎么做-Linux系统配置优化
    系统优化怎么做-SQL优化
    系统优化怎么做-数据库优化
    系统优化怎么做-新系统上线前做什么
    系统优化怎么做-开篇
    一起学习Avalonia(一)
    etcd的应用举例
    c#总结几种正则表达式使用
  • 原文地址:https://www.cnblogs.com/bbsno1/p/3279744.html
Copyright © 2011-2022 走看看