zoukankan      html  css  js  c++  java
  • hdu 1005 矩阵快速幂

    题意:A number sequence is defined as follows: f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7。Given A, B, and n, you are to calculate the value of f(n).
    分析:
    这题以前做过,还写了个题解:hdu 1005
    对于这题,主要是将做给的那个公式转化成矩阵的形式。
    | f[n] |= |A B|*| f[n-1] |
    | f[n-1] | |1 0| | f[n-2] |

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    typedef long long ll;
    const int mod=7;
    const int N=2;
    
    struct Mat{
        int mat[N][N];
    };
    int n=2,A,B;
    Mat mul(Mat a,Mat b)
    {
        Mat c; memset(c.mat,0,sizeof(c.mat));
        for(int k=0;k<n;k++)
        for(int i=0;i<n;i++)
        for(int j=0;j<n;j++){
            c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
            c.mat[i][j]%=mod;
        }
        return c;
    }
    Mat qmod(Mat a,int k)
    {
        Mat c;
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
            c.mat[i][j]=(i==j);
        for(;k;k>>=1){
            if(k&1)c=mul(c,a);
            a=mul(a,a);
        }
        return c;
    }
    int main()
    {
        int k;
        while(~scanf("%d%d%d",&A,&B,&k)&&(A+B+k)){
            if(k==1||k==2){
                printf("1
    ");continue;
            }
            Mat a;
            a.mat[0][0]=A%mod; a.mat[0][1]=B%mod;
            a.mat[1][0]=1; a.mat[1][1]=0;
            Mat c=qmod(a,k-2);
            printf("%d
    ",(c.mat[0][0]+c.mat[0][1])%mod);
        }
        return 0;
    }
  • 相关阅读:
    微服务架构综述
    何为正确
    如何在github中写出自己的readme文件
    redhat中如何在一块网卡上创建多个虚拟IP
    Vim 编辑器与shell命令脚本
    管道符、重定向与环境变量
    linux常用命令
    Android性能优化总结
    HTTP 协议漫谈
    Zxing QRCode
  • 原文地址:https://www.cnblogs.com/01world/p/5651257.html
Copyright © 2011-2022 走看看