zoukankan      html  css  js  c++  java
  • POJ3070 斐波那契数列递推 矩阵快速幂模板题

    题目分析:

    对于给出的n,求出斐波那契数列第n项的最后4为数,当n很大的时候,普通的递推会超时,这里介绍用矩阵快速幂解决当递推次数很大时的结果,这里矩阵已经给出,直接计算即可

     1 #include<iostream>
     2 #include<stdio.h>
     3 using namespace std;
     4 
     5 const int mod = 10000;
     6 struct mat{
     7     int m[2][2];
     8 };
     9 
    10 mat operator * (mat a, mat b){        //重载乘号,同时将数据mod10000 
    11     mat ret;
    12     for(int i = 0; i < 2; i++){
    13         for(int j = 0; j < 2; j++){
    14             long long temp = 0;
    15             for(int k = 0; k < 2; k++){
    16                 temp += a.m[i][k] * b.m[k][j];
    17                 temp %= mod;
    18             }
    19             ret.m[i][j] = temp;
    20         }
    21     }    
    22     return ret;
    23 }
    24 
    25 mat pow_mat(mat a, int n){        //矩阵快速幂和快速幂相同(广义快速幂的思想) 
    26     mat res = a;
    27     while(n){
    28         if(n&1) res = res * a;
    29         a = a*a;
    30         n >>= 1;
    31     }
    32     return res;
    33 }
    34 
    35 int main(){
    36     int n;
    37     while(scanf("%d", &n) !=EOF){
    38         if(n == -1) break;
    39         if(n == 0) printf("0
    ");
    40         else if(n == 1) printf("1
    ");
    41         else if(n == 2) printf("1
    ");
    42         else{
    43             mat a;                            //构造一个初始的矩阵 其n-2次方的m[0][0]就是所求的答案 
    44             a.m[0][0] = 1;
    45             a.m[0][1] = 1;
    46             a.m[1][0] = 1;
    47             a.m[1][1] = 0;
    48             mat ans = pow_mat(a, n-2);        //调用矩阵快速幂计算 
    49             printf("%d
    ", ans.m[0][0]);
    50         }
    51     }
    52     return 0;
    53 }
  • 相关阅读:
    Leetcode 121. Best Time to Buy and Sell Stock
    Leetcode 120. Triangle
    Leetcode 26. Remove Duplicates from Sorted Array
    Leetcode 767. Reorganize String
    Leetcode 6. ZigZag Conversion
    KMP HDU 1686 Oulipo
    多重背包 HDU 2844 Coins
    Line belt 三分嵌套
    三分板子 zoj 3203
    二分板子 poj 3122 pie
  • 原文地址:https://www.cnblogs.com/YLTFY1998/p/11805411.html
Copyright © 2011-2022 走看看