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;
    }
  • 相关阅读:
    luogu P3398 仓鼠找sugar
    关于lca
    luogu P3374 【模板】树状数组 1
    [NOIp2013普及组]车站分级
    [HDU1598]find the most comfortable road
    [NOI2015]程序自动分析
    [USACO08DEC]Secret Message
    [洛谷3375]【模板】KMP字符串匹配
    [ZJOI2010]网络扩容
    [SCOI2007]修车
  • 原文地址:https://www.cnblogs.com/01world/p/5651257.html
Copyright © 2011-2022 走看看