题目不难懂。式子是一个递推式,并且不难发现f[n]都是a的整数次幂。(f[1]=a0;f[2]=ab;f[3]=ab*f[2]c*f[1]...)

我们先只看指数部分,设h[n]. 则

h[1]=0;

h[2]=b;

h[3]=b+h[2]*c+h[1];

h[n]=b+h[n-1]*c+h[n-1].

h[n]式三个数之和的递推式,所以就可以转化为3x3的矩阵与3x1的矩阵相乘。于是

h[n]       c  1  b    h[n-1]

h[n-1]  =  1  0  0  *  h[n-2] 

1           0  0  1       1

又根据费马小定理(ap-1%p=1,p是质数且a,p互质)可得:ah[n]%mod=ah[n]%(mod-1)%mod.

因为 ah[n]%mod= ax*(mod-1)+h[n]%(mod-1)%mod = ax*(mod-1)*ah[n]%(mod-1)%mod = ah[n]%(mod-1)%mod;

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std; typedef long long ll;
ll p;
struct Mat
{
ll mat[][];
};
Mat Multiply(Mat a, Mat b)
{
Mat c;
memset(c.mat, , sizeof(c.mat));
for(int k = ; k < ; ++k)
for(int i = ; i < ; ++i)
if(a.mat[i][k])
for(int j = ; j < ; ++j)
if(b.mat[k][j])
c.mat[i][j] = (c.mat[i][j] +a.mat[i][k] * b.mat[k][j])%(p-);
return c;
}
Mat QuickPower(Mat a, ll k)
{
Mat c;
memset(c.mat,,sizeof(c.mat));
for(int i = ; i <; ++i)
c.mat[i][i]=;
for(; k; k >>= )
{
if(k&) c = Multiply(c,a);
a = Multiply(a,a);
}
return c;
}
ll Powermod(ll a,ll b)
{
a%=p;
ll ans=;
for(; b; b>>=)
{
if(b&) ans=(ans*a)%p;
a=(a*a)%p;
}
return ans;
}
int main()
{
//freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
ll n,a,b,c;
Mat x;
while(T--)
{
scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&p);
if(n==)
printf("1\n");
else if(n==)
printf("%I64d\n",Powermod(a,b));
else
{
x.mat[][]=c; x.mat[][]=; x.mat[][]=b;
x.mat[][]=; x.mat[][]=; x.mat[][]=;
x.mat[][]=; x.mat[][]=; x.mat[][]=;
x=QuickPower(x,n-);
ll k=(x.mat[][]*b+x.mat[][]);
printf("%I64d\n",Powermod(a,k));
}
}
return ;
}

最新文章

  1. chrome扩展程序开发
  2. 实现UITextView的placeholder
  3. 配置文件之SharedPreferences
  4. hihocoder 1391 [扫描线]
  5. Retrofit源码设计模式解析(上)
  6. AsyncTask下载网络图片
  7. ThinkPad告别蓝快,自己使用VHD安 WIN8.1并成功激活
  8. jdk与eclipse版本问题解决applet的启动
  9. UVALive 5881 Unique Encryption Keys (DP)
  10. AD设计中,三种大面积覆铜的区别
  11. nojs iis asp.net mvc
  12. iOS动画案例(2) 仿网易新闻标题动画
  13. canvas描绘渐变的矩形
  14. Dynamics 365 Customer Engagement安装FAQ
  15. 四大解析器(BeautifulSoup、PyQuery、lxml、正则)性能比较
  16. Java基础系列--包装类
  17. freeswitch 获取当前网关通道数
  18. python闭包和延迟绑定
  19. leetcode 124. Binary Tree Maximum Path Sum 、543. Diameter of Binary Tree(直径)
  20. QA

热门文章

  1. viewpager的简单使用,以及ValueAnimator的用法示例
  2. 如何通过XShell传输文件
  3. [PaPaPa][需求说明书][V0.3]
  4. 关于bootstrapValidator提交问题的解决
  5. IOS内存管理学习笔记
  6. C++ Copy Elision
  7. 同程旅游网开放平台SDK开发完成
  8. Netty5 + Protobuf 使用
  9. ORM:ODB安装使用过程
  10. mysql提示:Illegal mix of collations for operation ‘UNION’