HDOJ 4990 Reading comprehension(矩阵快速幂)
2016-02-18 20:26
211 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4990
题目大意:根据给出的代码,计算出答案。题目给出代码时间复杂度为o(n)=n,在正常情况下显然是超时的,所以我们需要使用矩阵快速幂来把时间复杂度降为O(n)=logn.
根据题意可以知道该表达式公式为
![](http://img.blog.csdn.net/20160218202605137)
合并可得公式
![](http://img.blog.csdn.net/20160218202632202)
(判断n的奇偶性在最后进行特殊处理)
然后根据递推式可得矩阵乘法公式
![](http://img.blog.csdn.net/20160218202758841)
套用矩阵快速幂模板 即可得到最后的答案;
题目大意:根据给出的代码,计算出答案。题目给出代码时间复杂度为o(n)=n,在正常情况下显然是超时的,所以我们需要使用矩阵快速幂来把时间复杂度降为O(n)=logn.
根据题意可以知道该表达式公式为
合并可得公式
(判断n的奇偶性在最后进行特殊处理)
然后根据递推式可得矩阵乘法公式
套用矩阵快速幂模板 即可得到最后的答案;
#include<iostream> #include<cstdio> #include<set> #include<string> #include<string.h> #include<cstring> #include<vector> #include<map> #include<queue> #include<stack> #include<cctype> #define inf 1000000000000000+7 using namespace std; typedef long long ll; typedef struct aaa { ll m[2][2]; }aaa; aaa mulM(aaa &x ,aaa& y,ll mod) { aaa temp; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { temp.m[i][j] = 0; for (int k = 0; k < 2; k++) { temp.m[i][j] = (temp.m[i][j] + x.m[i][k] * y.m[k][j] % mod) % mod; } } } return temp; } int main() { ll n, mod; aaa a; a.m[0][0] = 4; a.m[0][1] = 0; a.m[1][0] = 2; a.m[1][1] = 1; aaa E; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { E.m[i][j] = 0; } } E.m[0][1] = 1; while (scanf("%lld %lld", &n, &mod) != EOF) { aaa ans = E; aaa mul = a; ll nn = n ; if (n & 1)nn--; nn /= 2; while (nn) { if (nn & 1)ans = mulM(ans, mul,mod); mul = mulM(mul, mul, mod); nn >>= 1; } //ans.m[0][0] = ans.m[1][0]; if (n & 1)ans.m[0][0] = (2 * ans.m[0][0] + 1)%mod;//根据n的奇偶性的特殊处理 printf("%I64d\n", ans.m[0][0]); } return 0; }
相关文章推荐
- python面试问题题目
- 微信运动修改器python代码
- git 笔记
- mysql表结构查询
- linux之i2c子系统架构---总线驱动
- 回车换行知多少——关于回车换行的小插曲
- flask-sqlalchemy不同的关系的实例
- android基础--WebView
- USACO runaround
- 「深入Java」类型信息:RTTI和反射
- oracle之去重与排序
- C/C++程序中的profile http://blog.csdn.net/cnjet/article/details/2617403
- 【图像处理】空间变换
- Java基础知识点3:集合类
- 基于redis ae实现 Linux中的文件系统监控机制(inotify)
- SMART 原则
- 产品经理必读《结网》读书笔记
- javascript日历插件
- 算法题23 带min函数的栈
- JSP的自定义标签(一)