zoukankan      html  css  js  c++  java
  • POJ 3070 Fibonacci(矩阵乘法logN)

    题意:

    求第n个斐波那契数,结果mod10000.

    思路:

    矩阵的n次方可以由二分法来解决,于是把时间缩短到了logN

    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    
    const int M = 10000;
    
    typedef struct _Matrix {
        int v[2][2];
    } Matrix;
    
    Matrix m;
    
    Matrix matrix_mul(Matrix a, Matrix b)
    {
        Matrix c;
        c.v[0][0] = (a.v[0][0] * b.v[0][0] + a.v[0][1] * b.v[1][0]) % M;
        c.v[0][1] = (a.v[0][0] * b.v[0][1] + a.v[0][1] * b.v[1][1]) % M;
        c.v[1][0] = (a.v[1][0] * b.v[0][0] + a.v[1][1] * b.v[1][0]) % M;
        c.v[1][1] = (a.v[1][0] * b.v[0][1] + a.v[1][1] * b.v[1][1]) % M;
        return c;
    }
    
    Matrix matrix_pow(Matrix b, int n)
    {
        if (n == 1)
            return b;
        Matrix c = matrix_pow(b, n >> 1);
        if (n % 2)
            return matrix_mul(matrix_mul(c, c), m);
        else
            return matrix_mul(c, c);
    }
    
    int main()
    {
        int n;
        m.v[0][0] = 1, m.v[0][1] = 1;
        m.v[1][0] = 1, m.v[1][1] = 0;
        
        while (scanf("%d", &n) && n != -1)
        {
            if (n == 0) {
                printf("0\n");
                continue;
            }
            Matrix b;
            b = matrix_pow(m, n);
            printf("%d\n", b.v[1][0]);
        }
        return 0;
    }
    -------------------------------------------------------

    kedebug

    Department of Computer Science and Engineering,

    Shanghai Jiao Tong University

    E-mail: kedebug0@gmail.com

    GitHub: http://github.com/kedebug

    -------------------------------------------------------

  • 相关阅读:
    js(四) 全选/全不选和反选
    js(三) ajax异步局部刷新技术底层代码实现
    js(二) 实现省市联动(json)
    接口
    内部类
    封装
    Static关键字
    this关键字
    带参数的方法
    abstract关键字
  • 原文地址:https://www.cnblogs.com/kedebug/p/2792333.html
Copyright © 2011-2022 走看看