zoukankan      html  css  js  c++  java
  • 2016级算法第一次练习赛-C.斐波那契进阶

    870 斐波那契进阶

    题目链接:https://buaacoding.cn/problem/870/index

    思路

    通过读题就可以发现这不是一般的求斐波那契数列,所以用数组存下所有的答案是不现实的。题目也明确点明此题可以利用矩阵的计算解题。

    如果你稍微百度一下你会了解到快速矩阵幂的概念。

    什么是快速矩阵幂?

    分析

    快速矩阵幂算法是一种简单的具有典型意义的连续为离散算法,同学们一定要掌握其思想,而不是从网上copy一份板子就用。

    时间复杂度:(O(lgN))

    考点:简单的快速矩阵幂;

    坑点:一边计算一边取模才不会找过范围。

    参考代码

    //
    // Created by AlvinZH on 2017/10/1.
    // Copyright (c) AlvinZH. All rights reserved.
    //
    
    #include <cstdio>
    #include <cstring>
    #include <cstdlib>
    #include <cmath>
    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <map>
    #include <set>
    #include <queue>
    #include <string>
    #include <bitset>
    #include <utility>
    #include <functional>
    #include <iomanip>
    #include <sstream>
    #include <ctime>
    #define INF 0x3f3f3f3f
    #define eps 1e-8
    #define MaxSize 100005
    #define MOD 10007
    typedef long long LL;
    using namespace std;
    
    const int N = 2;
    
    struct Matrix {
        int mat[N][N];
        Matrix() {}
        Matrix operator * (const Matrix& b) const {
            Matrix result;
            memset(result.mat, 0, sizeof(result.mat));
            for (int i = 0; i < N; ++i) {
                for (int j = 0; j < N; ++j) {
                    for (int k = 0; k < N; ++k) {
                        result.mat[i][j] = (result.mat[i][j] + this->mat[i][k] * b.mat[k][j]) % MOD;
                    }
                }
            }
            return result;
        }
    };
    
    Matrix MatPow(Matrix base, int n)
    {
        Matrix result;
        memset(result.mat, 0, sizeof(result.mat));
        for (int i = 0; i < N; ++i) {
            result.mat[i][i] = 1;
        }
    
        while (n > 0)
        {
            if(n & 1) result = result * base;
            base = base * base;
            n >>= 1;
        }
        return result;
    }
    
    int main()
    {
        Matrix base;
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < N; ++j) {
                base.mat[i][j] = 1;
            }
        }
        base.mat[1][1] = 0;
        int n;
        while (~scanf("%d", &n))
        {
            Matrix ans = MatPow(base, n);
            printf("%d
    ", ans.mat[0][1]);
        }
    }
    
  • 相关阅读:
    Webservice里使用Linq遇到ToList输出泛型而产生循环引用错误的解决办法(转)
    JavaScript 面向对象程序设计(转)
    SilverLight中的基本图形(转)
    JQuery常用方法一览(转)
    常用的JS(转)
    简单的java socket 服务器端
    Eclipse RCP 之国际化(转载)
    使用Eclipse构建GeoTools项目
    java.lang.UnsatisfiedLinkError: no XX in java.library.path解决方法
    sqlite第三方类库:FMDB使用(转载)
  • 原文地址:https://www.cnblogs.com/AlvinZH/p/7698968.html
Copyright © 2011-2022 走看看