FZU 2198 快来快来数一数(矩阵快速幂)

/*
a[i]=6*a[i-1]-a[i]+1;

矩阵快速幂+预处理

vc++可过。。。。
*/
# include 
# include 
# include 
# include 
using namespace std;
struct node
{
    __int64 m[3][3];
};
const __int64 mod=1000000007;
node f(node a,node b)
{
    int i,j,k;
    node c;
    for(i=0; i<3; i++)
        for(j=0; j<3; j++)
        {
            c.m[i][j]=0;
            for(k=0; k<3; k++)
            {
                c.m[i][j]=(c.m[i][j]+((a.m[i][k]*b.m[k][j]))+mod)%mod;
                //c.m[i][j]%=mod;
            }
        }
    return c;
}
node quick(node origin,__int64 n)
{

    node answ;
    memset(answ.m,0,sizeof(answ));
    for(int i=0; i<3; i++)
        answ.m[i][i]=1;
    while(n)
    {
        if(n%2==1)
        {
            answ=f(origin,answ);

        }
        origin=f(origin,origin);
        n/=2;
    }
    return answ;
}

int main()
{


    int t;
    __int64 n;
    node o,answ;
    memset(o.m,0,sizeof(o.m));
    o.m[0][0]=6;
    o.m[0][1]=1;
    o.m[1][0]=-1;
    o.m[2][0]=1;
    o.m[2][2]=1;

    memset(answ.m,0,sizeof(answ.m));
    answ.m[0][0]=7;
    answ.m[0][1]=1;
    answ.m[0][2]=1;

    node hehe[80];
    hehe[1]=o;
    for(int i=2; i<70; i++)//预处理
    {
        hehe[i]=f(hehe[i-1],hehe[i-1]);
    }
    while(~scanf("%d",&t))
    {
        while(t--)
        {
            scanf("%I64d",&n);
            if(n==1)
                printf("6\n");
            else if(n==2)
                printf("41\n");
            else
            {
                node B;
                memset(B.m,0,sizeof(B.m));
                n--;
                for(int i=0; i<3; i++)
                    B.m[i][i]=1;
                for (int i = 1; n; i++, n >>= 1)
                {
                    if (n&1)
                        B=f(B, hehe[i]);
                }
                node t=f(answ,B);
                printf("%I64d\n",(t.m[0][0]-1+mod)%mod);
            }
        }
    }
    return 0;
}

你可能感兴趣的:(FZU 2198 快来快来数一数(矩阵快速幂))