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\n");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\n",(c.mat[0][0]+c.mat[0][1])%mod);
    }
    return 0;
}
posted @ 2016-03-22 18:38  HARD_UNDERSTAND  阅读(130)  评论(0编辑  收藏  举报