1. 程式人生 > >hdu 5667 Sequence【矩陣快速冪】

hdu 5667 Sequence【矩陣快速冪】

Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 285    Accepted Submission(s): 92


Problem Description Holion August will eat every thing he has found.

Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.

f
n
=1,ab,abfcn1fn2,n=1n=2otherwise


He gives you 5 numbers n,a,b,c,p,and he will eat fn foods.But there are only p foods,so you should tell him fn mod p.
Input The first line has a number,T,means testcase.

Each testcase has 5 numbers,including n,a,b,c,p in a line.

1T10,1n1018,1a,b,c109,p is a prime number,and p
109+7
.
Output Output one number for each case,which is fn mod p.  Sample Input
1
5 3 3 3 233
 


Sample Output
190

題目大意:根據給出的公式,求其解fn、

思路:根據公式得出結論,求的的fn,一定是a的多少次方,所以我們鎖定思路是求a的冪數。然後再用快速冪求出解。

公式不難推出:

Fn=Fn-1*c+Fn-2+b;

然後我們也不難寫出矩陣:


坑點:在矩陣快速冪的時候要注意先對mod-1,再進行。也就是要注意amodp==0的情況。

然後再進行a的這些次方即可。

Ac程式碼:

#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
#define ll long long int
ll mod;
typedef struct Matrix
{
    ll mat[3][3];
} matrix;
matrix A,B,tmp;
Matrix matrix_mul(matrix a,matrix b)
{
    matrix c;
    memset(c.mat,0,sizeof(c.mat));
    int i,j,k;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            for(int k=0; k<3; k++)
            {
                c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
                c.mat[i][j]%=mod;
            }
        }
    }
    return c;
}
Matrix matrix_quick_power(matrix a,ll k)//矩陣快速冪0.0
{
    matrix b;
    memset(b.mat,0,sizeof(b.mat));
    for(int i=0; i<3; i++)
        b.mat[i][i]=1;//單位矩陣b
    while(k)
    {
        if(k%2==1)
        {
            b=matrix_mul(a,b);
            k-=1;
        }
        else
        {
            a=matrix_mul(a,a);
            k/=2;
        }
    }
    return b;
}
ll Mod_pow(ll a, ll b, ll p)
{
    a %= p;
    ll ans = 1ll;
    while (b)
    {
        if (b & 1)ans = ans*a%p;
        a = a*a%p;
        b >>= 1;
    }
    return ans;
}
int main()
{
    ll n,a,b,c;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%I64d%I64d%I64d%I64d%I64d", &n, &a, &b, &c, &mod);
        A.mat[0][0] = c, A.mat[0][1] = 1, A.mat[0][2] = b;
        A.mat[1][0] = 1, A.mat[1][1] = 0, A.mat[1][2] = 0;
        A.mat[2][0] = 0, A.mat[2][1] = 0, A.mat[2][2] = 1;
        if (n == 1)printf("1\n");
        else if (n == 2)printf("%I64d\n", Mod_pow(a, b, mod));
        else
        {
            mod--;
            B =  matrix_quick_power(A,(n - 2));
            ll tmp=B.mat[0][0]*b+B.mat[0][2];
            mod++;
            ll ans = Mod_pow(a, tmp, mod);
            printf("%I64d\n",ans);
        }
    }
}