hdoj 5667 Sequence(矩阵快速幂、费马小定理)

看着就像是要用矩阵做,但是有个a^b,不知道怎么去推递推式。


思路:对两边取a为底的对数,就可以得到


loga(fn) = c*loga(fn-1) + loga(fn-2) + b,然后令Fn = loga(fn), 


可以得到Fn = c*Fn-1 + Fn-2 + b


之后构造矩阵快速幂就行了,得到Fn, fn = a^(Fn), 要mod p,指数


又特别大,所以需要用到费马小定理了(a^x≡a^(x%(p-1))(mod p)).


看到有人说需要加个特判, a是p的倍数时应该输出0。但测试数据没有a事p的倍数,所以

不加也没事。


参考博客:点击打开链接


代码:

#include
using namespace std;
typedef long long ll;
ll n, a, b, c, p;

struct node
{
    ll s[3][3];
    node() { memset(s, 0, sizeof(s)); }
};

node mul(node a, node b)
{
    node t;
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            for(int k = 0; k < 3; k++)
                t.s[i][j] = (t.s[i][j]+a.s[i][k]*b.s[k][j])%(p-1);
    return t;
}

node mt_pow(node p, ll k)
{
    node q;
    for(int i = 0; i < 3; i++) q.s[i][i] = 1;
    while(k)
    {
        if(k&1) q = mul(p, q);
        p = mul(p, p);
        k /= 2;
    }
    return q;
}

ll po(ll x, ll y)
{
    ll ans = 1;
    while(y)
    {
        if(y&1) ans = (ans*x)%p;
        x = x*x%p;
        y /= 2;
    }
    return ans;
}

int main(void)
{
    int t;
    cin >> t;
    while(t--)
    {
        scanf("%lld%lld%lld%lld%lld", &n, &a, &b, &c, &p);
        if(n == 1) puts("1");
        else if(a % p == 0) puts("0");
        else
        {
            node base;
            base.s[0][0] = c; base.s[0][1] = 1;
            base.s[0][2] = 1; base.s[1][0] = 1;
            base.s[2][2] = 1;

            node ans = mt_pow(base, n-2);
            ll P = (ans.s[0][0]+ans.s[0][2])*b%(p-1);
            printf("%lld\n", po(a, P)%p);
        }
    }
    return 0;
}


Sequence

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


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.

fn=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  p109+7.
 

Output
    Output one number for each case,which is  fn mod p.
 

Sample Input
 
   
1 5 3 3 3 233
 

Sample Output
 
   
190
 

Source
BestCoder Round #80
 

Recommend
wange2014   |   We have carefully selected several similar problems for you:   5981  5980  5979  5978  5977 



你可能感兴趣的:(数学,矩阵)