题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4291

题目意思:求g(g(g(n))) mod 109 + 7,其中g(n) = 3g(n - 1) + g(n - 2),g(1) = 1,g(0) = 0。

思路:一个很简单的矩阵快速幂,简单的想法就是先用n算出g(n),然后再算g(g(n)),然后再算最外层,都是mod(1e9+7),这么做就错了,这道题有一个循环节的问题,看来这种嵌套的递推式取mod是存在循环节的,以后要注意下。

计算循环节的代码(貌似方法叫做弗洛伊德判圈法?):

 #include <cstdio>
#include <iostream>
using namespace std;
#define LL __int64
LL mod=1e9+;
int main()
{
LL i,a,b,g;
a=,b=;
for(i=;;i++)
{
g=(*a+b)%mod;
b=a;
a=g;
if(a==&&b==)
{
if(i!=mod) {mod=i;}
else break;
cout<<i<<endl;
i=;
}
}
return ;
}

代码:

 #include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std; typedef __int64 int64;
const int N = ; int64 n;
struct Matrix{
int64 mat[N][N];
int64 MOD;
Matrix operator*(const Matrix& m)const{
Matrix tmp;
tmp.MOD = MOD;
for(int i = ; i < N ; i++){
for(int j = ; j < N ; j++){
tmp.mat[i][j] = ;
for(int k = ; k < N ; k++)
tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%MOD;
tmp.mat[i][j] %= MOD;
}
}
return tmp;
}
}; int64 Pow(Matrix m , int64 x , int64 MOD){
if(x <= ) return x;
Matrix ans;
ans.MOD = m.MOD = MOD;
ans.mat[][] = ans.mat[][] = ;
ans.mat[][] = ans.mat[][] = ;
x--;
while(x){
if(x%)
ans = ans*m;
x /= ;
m = m*m;
}
return ans.mat[][]%MOD;
} // 暴力找到循环节
int64 getLoop(int64 MOD){
int64 pre1 = ;
int64 pre2 = ;
for(int64 i = ; ; i++){
int64 x = *pre1%MOD+pre2%MOD;
x %= MOD;
// update
pre2 = pre1;
pre1 = x;
int64 y = *pre1%MOD+pre2%MOD;
if(x == && y == ){
return i;
}
}
} int main(){
int64 L1 = 1e9+;
int64 L2 = ;
int64 L3 = ;
Matrix m;
m.mat[][] = ; m.mat[][] = ;
m.mat[][] = ; m.mat[][] = ;
while(scanf("%I64d" , &n) != EOF){
int64 x = Pow(m , n , L3);
int64 y = Pow(m , x , L2);
int64 ans = Pow(m , y , L1);
printf("%I64d\n" , ans);
}
return ;
}

最新文章

  1. FreeRTOS run on eclipse
  2. python 循环定时器
  3. 看看如何面试前端工程师:Github很重要
  4. gpg: no valid OpenPGP data found
  5. Unable to resolve module LinkedStateMixin
  6. UIScrollView解决touchesBegan等方法不能触发的解方案
  7. js实现placeholder效果
  8. 谈谈自己对于Auth2.0的见解
  9. 里氏替换原则LSP(继承规范)
  10. Thrift源码解析--TBinaryProtocol
  11. Get the Job You Want(大学英语综合教程4课文)
  12. web.xml配置web中的key points(下)
  13. babel (二) update to v7
  14. 记录安装 java 环境,部署环境变量遇到的小坑
  15. MT【59】一道迭代函数作图
  16. (21)模型层 -ORM之msql 聚合查询,F和Q(与、或、非查询)、分组查询
  17. Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of
  18. Linux基础命令---e2fsck
  19. uva-10420-排序
  20. 【转】HttpWebRequest 保持session

热门文章

  1. [svc]centos6系统安装(分区)及其18处调优调优最佳实战
  2. Objective-C函数重载规则
  3. iOS开发总结-Xcode常见错误
  4. 用C语言(apue)实现 把时间戳转换为国标格式的字符串(2017-07-17 22:36:12)的函数
  5. oracle 函数判断字符串是否包含图片格式
  6. getAttribute()方法
  7. 在sql结果中显示行号
  8. 向服务器发送josn字符串,服务器端解析
  9. List接口的实现类与ArrayList相似,区别是Vector是重量级的组件,使用使消耗的资源比较多
  10. 嵌入式驱动开发之采集方式bypass mode---bypass mode