矩阵快速幂 POJ 3070 Fibonacci
2015-07-31 20:34
381 查看
题目传送门
/* 矩阵快速幂:求第n项的Fibonacci数,转置矩阵都给出,套个模板就可以了。效率很高啊 */ #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> using namespace std; const int MAXN = 1e3 + 10; const int INF = 0x3f3f3f3f; const int MOD = 10000; struct Mat { int m[2][2]; }; Mat multi_mod(Mat a, Mat b) { Mat ret; memset (ret.m, 0, sizeof (ret.m)); for (int i=0; i<2; ++i) { for (int j=0; j<2; ++j) { for (int k=0; k<2; ++k) { ret.m[i][j] = (ret.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD; } } } return ret; } int matrix_pow_mod(Mat x, int n) { Mat ret; ret.m[0][0] = ret.m[1][1] = 1; ret.m[0][1] = ret.m[1][0] = 0; while (n) { if (n & 1) ret = multi_mod (ret, x); x = multi_mod (x, x); n >>= 1; } return ret.m[0][1]; } int main(void) { //POJ 3070 Fibonacci int n; while (scanf ("%d", &n) == 1) { if (n == -1) break; Mat x; x.m[0][0] = x.m[0][1] = x.m[1][0] = 1; x.m[1][1] = 0; printf ("%d\n", matrix_pow_mod (x, n)); } return 0; }
相关文章推荐
- Nim
- spring与hibernate整合(三种方式)
- 快速数论变换模板(NTT)
- 已知面积求周长
- Radar Installation(贪心,可以转化为今年暑假不ac类型)
- 【暑假集训】之被ACM金牌大神虐的第一天之dp篇(未完结)
- 数据挖掘工程师面试指南
- XMLHttpRequest Level 2的跨域功能(CORS) //另附JSONP的跨域实现
- AJAX 利用 XHR2 Progress Event 實作下載進度列
- 7_31_html_css样式
- iOS-01-UILabel
- 2037 今年暑假不AC【贪心】
- 栈和队列
- IBM Minus One
- 跨域的三种方法总结:代理,JSONP,以及XHR2
- 字符串的全排列和组合算法
- HDOJ 题目4099 Revenge of Fibonacci(大数, 字典树)
- Maximal Rectangle
- HDU-4810 Wall Painting
- Excel数据导入___你hold住么(二)