Hdu5950 recursive sequence (fast power of matrix)

Posted by whmeeske on Thu, 19 Dec 2019 17:01:24 +0100

Title Link: Recursive sequence

Wh a t's the num b er of the nth cow

Main idea:

  Fi=Fi-1+2Fi-2+i4. Given F1 and F2, find Fn.

Topic idea:

[recurrence + matrix fast power]

The formula has been used for more than one hour.

It's mainly me. Too few tweets.

It is easy to write recursive matrix by first considering f(i)=f(i-1)+2f(i-2)

    0 2

    1 1

  (i+1)4=i4+4i3+6i2+4i+1.

So we need to store the power of i to the power of 432110 in the recursive matrix, so that we can deduce (i+1)4. The matrix is

    1 0 0 0 0

    4 1 0 0 0

    6 3 1 0 0

    4 3 2 1 0

    1 1 1 1 1

Then f = {f I-1, fi, I4, I3, I2, I1, I0}. By combining the above two matrices, we can deduce {fi,fi+1,(i+1)4,(i+1)3,(i+1)2,(i+1)1,(i+1)0}

    0 2 0 0 0 0 0

    1 1 0 0 0 0 0

    0 1 1 0 0 0 0

    0 4 4 1 0 0 0

    0 6 6 3 1 0 0

    0 4 4 3 2 1 0

    0 1 1 1 1 1 1

After deriving the transfer matrix, we only need to find the fast power of the matrix according to n.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;
const long long mod = 2147493647;
struct prog
{
    long long a[8][8];
};
prog s,B;
prog matrixmul(prog a,prog b)
{
    prog c;
    for(int i=1;i<8;++i)for(int j=1;j<8;++j)
    {
        c.a[i][j]=0;
        for(int k=1;k<8;k++)
            c.a[i][j]+=(a.a[i][k]*b.a[k][j])%mod;
        c.a[i][j]%=mod;
    }
    return c;
}
prog mul(prog s,int k)
{
    prog ans;
    for(int i=1;i<8;++i)for(int j=1;j<8;++j) ans.a[i][j]=(i==j)?1:0;
    while(k){
        if(k&1)
            ans=matrixmul(ans,s);
        k>>=1;
        s=matrixmul(s,s);
    }
    return ans;
}
int main()
{
    int n,t,a,b;
    for(scanf("%d",&t);t--;){
        scanf("%d %d %d",&n,&a,&b);
        if(n==1){printf("%lld\n",a%mod);continue;}
        if(n==2){printf("%lld\n",b%mod);continue;}
        if(n==3){printf("%lld\n",(81+2*a%mod+b%mod)%mod);continue;} 
        n-=2;
        for(int i=1;i<=7;++i)for(int j=1;j<=7;++j) s.a[i][j]=0,B.a[i][j]=0;
        for(int i=1; i<=5; i++)s.a[i][1]=1;
        for(int i=2; i<=5; i++)s.a[i][2]=i-1;
        s.a[3][3]=1;s.a[4][3]=3;s.a[5][3]=6;
        s.a[4][4]=1;s.a[5][4]=4;
        s.a[5][5]=1;s.a[6][5]=1;
        s.a[6][6]=1;s.a[7][6]=1;
        s.a[6][7]=2;
        B.a[1][1]=1;B.a[2][1]=3;B.a[3][1]=9;B.a[4][1]=27;B.a[5][1]=81;B.a[6][1]=b;B.a[7][1]=a;
        s=mul(s,n);
        s=matrixmul(s,B);
        printf("%lld\n",s.a[6][1]%mod);
    }
    return 0;
}