hdu 2855(矩阵快速幂)
2015-05-31 22:11
393 查看
题意:计算公式
![](http://acm.hdu.edu.cn/data/images/convip2-1003-1.jpg)
题解:想推出矩阵相乘的形式,想了很久也想不出,然后看别人的题解有一个高中就学过的式子:
(1 + x) ^ n = Cn0x^n+Cn1x^(n-1)+Cn2x^(n-2)+Cn3x^(n-3)+····+Cnn
然后想到斐波那契矩阵是{1,1,1,0},1看做一个单位阵{1,0,1,0},就会做了。。。
![](http://poj.org/images/3070_1.png)
![](http://acm.hdu.edu.cn/data/images/convip2-1003-1.jpg)
题解:想推出矩阵相乘的形式,想了很久也想不出,然后看别人的题解有一个高中就学过的式子:
(1 + x) ^ n = Cn0x^n+Cn1x^(n-1)+Cn2x^(n-2)+Cn3x^(n-3)+····+Cnn
然后想到斐波那契矩阵是{1,1,1,0},1看做一个单位阵{1,0,1,0},就会做了。。。
![](http://poj.org/images/3070_1.png)
#include <stdio.h> #include <string.h> int n, m; struct Mat { int g[2][2]; }ori, res; Mat multiply(Mat x, Mat y) { Mat temp; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) { temp.g[i][j] = 0; for (int k = 0; k < 2; k++) temp.g[i][j] = (temp.g[i][j] + x.g[i][k] * y.g[k][j]) % m; } return temp; } void calc(int n) { while (n) { if (n & 1) res = multiply(res, ori); n >>= 1; ori = multiply(ori, ori); } } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &m); ori.g[0][0] = 2; ori.g[0][1] = ori.g[1][0] = ori.g[1][1] = 1; res.g[0][0] = res.g[1][1] = 1; res.g[0][1] = res.g[1][0] = 0; calc(n); printf("%d\n", res.g[0][1]); } return 0; }
相关文章推荐
- 黑马程序员---找出指定文件夹.java文件,列出他们的绝对路径,并计算出数量
- akka概述
- WorldWind源码剖析系列:外包围盒类BoundingBox和外包围球类BoundingSphere
- Zigbee温湿度压力监测设计
- hdu1847 Good Luck in CET-4 Everybody!(博弈论)
- PHP命名空间(Namespace)的使用详解
- 【项目实战】--Office文件导出
- WorldWind源码剖析系列:角度类Angle
- [Java5新特性]自动装箱/拆箱
- StringBuilder常用方法
- 五分钟一个设计模式之组合模式
- Python学习日记---字符串
- LINUX-软件安装(二)
- 生产环境超时库存回收优化
- ITOO3.0-我们的项目做的到底如何?
- 占座2
- 数据库数据优化故事多
- 【转】ubuntu安装ftp服务器
- [Java5新特性]自动装箱/拆箱
- WorldWind源码剖析系列:数学引擎类MathEngine