hdu1005 Number Sequence(矩阵快速幂)

题意:
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).
思路:
矩阵快速幂模板题。
构造转移矩阵为
( A B 1 1 0 0 0 0 1 ) \begin{pmatrix}A&B&1\\1&0&0\\0&0&1\end{pmatrix}
带入矩阵快速幂模板就行了。
注意特判 1 , 2 1,2 项,超时了很久。。。困恼~
A C   C o d e : AC \ Code:

#include<iostream>
#include<cstring>
#include<queue>
#include<map>
#include<cmath>
#include<set>
#include<stack>
#include<cstdio>
#include<sstream>
#include<vector>
#include<bitset>
#include<algorithm>

using namespace std;
#define read(x) scanf("%d",&x)
#define Read(x,y) scanf("%d%d",&x,&y)
#define gc(x)  scanf(" %c",&x);
#define mmt(x,y)  memset(x,y,sizeof x)
#define write(x) printf("%d\n",x)
#define pii pair<int,int>
#define INF 0x3f3f3f3f
#define ll long long
const int N = 100000 + 100;
const int M = 3e6 + 1005;
typedef long long LL;
LL mod;
struct mat
{
    LL m[5][5];//矩阵大小
    mat() {
       memset(m,0,sizeof(m));
    }
    mat operator * (mat &a ) {//重载 * 运算符
       mat ans;
       for (int i=0 ;i<3 ;i++  ){//矩阵乘法
          for (int k=0 ;k<3 ;k++) if(m[i][k]) {
              for (int j=0 ;j<3 ;j++) if(a.m[k][j]) {
                 ans.m[i][j]=(ans.m[i][j]+m[i][k]*a.m[k][j])%mod;//取模
              }
          }
       }
       return ans;
    }
};
mat mat_pow(mat a,LL b)//矩阵快速幂
{
    mat ans;
    for (int i=0 ;i<3 ;i++ ) ans.m[i][i]=1;//单位阵
    while(b) {
        if (b&1) ans=ans*a;
        b=b>>1;
        a=a*a;
    }
    return ans;
}
int main() {
    LL a,b,c;
    while(scanf("%lld%lld%lld",&a,&b,&c) == 3&&a + b + c){
        if(c == 1){
            puts("1");
            continue;
        }
        else if(c == 2){
            puts("1");
            continue;
        }
        LL mm[3][3] = {
            {a,b,1},
            {1,0,0},
            {0,0,1},
        };
        mat ans ;
        for(int i = 0;i < 3;++i){
            for(int j = 0;j < 3;++j){
                ans.m[i][j] = mm[i][j];
            }
        }
        LL n,m;
        n = c;m = 7;
        mod = m;
        ans = mat_pow(ans,n-2);
        printf("%lld\n",(ans.m[0][0]+ans.m[0][1]*1)%mod);
    }
}
发布了632 篇原创文章 · 获赞 27 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43408238/article/details/103597309