hdu 1005 Number Sequence 矩阵基础题

#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
const int mod=7;
struct matrix{
    int f[2][2];
};
matrix mul(matrix a,matrix b)
{
    int i,j,k;
    matrix c;
    memset(c.f,0,sizeof(c.f));
    for(i=0;i<2;i++)
        for(j=0;j<2;j++)
            for(k=0;k<2;k++)
            {
                c.f[i][j]+=a.f[i][k]*b.f[k][j];
                c.f[i][j]%=mod;
            }
    return c;
}
matrix pow_mod(matrix a,int b)
{
    matrix s;
    memset(s.f,0,sizeof(s.f));
    for(int i=0;i<2;i++)
        s.f[i][i]=1;
    while(b)
    {
        if(b&1)
            s=mul(s,a);
        a=mul(a,a);
        b=b>>1;
    }
    return s;
}
int main()
{
    int a,b,n;
    while(cin>>a>>b>>n)
    {
        if(a==0&&b==0&&n==0)break;
        matrix e;
        e.f[0][0]=a;e.f[0][1]=1;
        e.f[1][0]=b;e.f[1][1]=0;
        e=pow_mod(e,n-1);
        cout<<(e.f[0][1]+e.f[1][1])%mod<<endl;
    }
    return 0;
}
/*
    |f[n] f[n-1]|*|a 1|=|f[n+1] f[n]|
                  |b 0|
*/

你可能感兴趣的:(矩阵)