hdu 4291 矩阵快速幂+找循环节

#include<cstdio>
#include<cstring>
using namespace std;
#define ll __int64
ll a[3]={183120,222222224,1000000007};
const int N=2;
ll mod;
struct matrix
{
    ll mat[N][N];
};
matrix mul(matrix a,matrix b)
{
    matrix c;
    ll i,j,k;
    for(i=0;i<N;i++)
    {
        for(j=0;j<N;j++)
        {
            c.mat[i][j]=0;
            for(k=0;k<N;k++)
                (c.mat[i][j]+=(a.mat[i][k]*b.mat[k][j]))%=mod;
        }
    }
    return c;
}
matrix pow(matrix a,ll x)
{
    matrix b;
    memset(b.mat,0,sizeof(b.mat));
    for(ll i=0;i<N;i++)
        b.mat[i][i]=1;
    while(x)
    {
        if(x&1)b=mul(a,b);
        x>>=1;
        a=mul(a,a);
    }
    return b;
}
int main()
{
    ll n;
    while(scanf("%I64d",&n)!=EOF)
    {
        if(n==0){printf("0\n");continue;}
        matrix tmp,ans;
        tmp.mat[0][0]=3;tmp.mat[0][1]=1;
        tmp.mat[1][0]=1;tmp.mat[1][1]=0;
        for(int i=0;i<3;i++)//g(g(g(x)))mod 1e9+7--->g(g(x))有循环节222222224--->g(x)有循环节183120
        {
            mod=a[i];
            ans=pow(tmp,n-1);
            n=(ans.mat[0][0]==0?mod:ans.mat[0][0]);
        }
        printf("%I64d\n",n%mod);
    }
}

寻找循环节的代码

#include <cstdio>
#include <iostream>
using namespace std;
#define LL __int64
const LL mod1=1e9+7;
const LL mod2=222222224;
int main()
{
    LL i,a,b,g;
    a=1,b=0;
    for(i=1;;i++)
    {
        g=(3*a+b)%mod1;
        b=a;
        a=g;
        if(a==1&&b==0)
        {
            cout<<i<<endl;
            break;
        }
    }
    return 0;
}


你可能感兴趣的:(hdu 4291 矩阵快速幂+找循环节)