51nod 1126 求递推序列的第N项 矩阵快速幂
来源:互联网 发布:linux嵌入式开发 编辑:程序博客网 时间:2024/06/07 15:14
题目:
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1126
题意:
有一个序列是这样定义的:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
给出A,B和N,求f(n)的值。
Input
输入3个数:A,B,N。数字之间用空格分割。(-10000 <= A, B <= 10000, 1 <= N <= 10^9)
Output
输出f(n)的值。
思路
矩阵快速幂裸题,首先构造一个2*2的矩阵,矩阵元素从左至右从上至下分别是 a 1 b 0,求这个矩阵的n-2次幂,然后构造一个1*2的矩阵,元素分别是f(2) f(1),把这个矩阵与之前求得的幂相乘,得到的结果中第一行第一列的元素就是答案
#include <bits/stdc++.h>using namespace std;const int N = 10 + 10, MOD = 7;struct matrix{ int row, col; int mat[N][N]; matrix(int _row=0, int _col=0) { init(_row, _col); } void init(int _row, int _col) { row = _row, col = _col; memset(mat, 0, sizeof mat); } matrix operator* (matrix b) { matrix c(row, b.col); for(int i = 1; i <= row; i++) for(int j = 1; j <= b.col; j++) for(int k = 1; k <= col; k++) c.mat[i][j] = (c.mat[i][j] + mat[i][k] * b.mat[k][j] % MOD + MOD) % MOD; return c; }};matrix matrix_pow(matrix a, int b){ matrix ans(a.row, a.col); ans.mat[1][1] = ans.mat[2][2] = 1; while(b) { if(b & 1) ans = ans * a; b >>= 1; a = a * a; } return ans;}int main(){ int a, b, n; scanf("%d%d%d", &a, &b, &n); if(n <= 2) printf("%d\n", 1); else { matrix arr(2, 2); arr.mat[1][1] = a, arr.mat[2][1] = b; arr.mat[1][2] = 1, arr.mat[2][2] = 0; matrix brr(1, 2); brr.mat[1][1] = 1, brr.mat[1][2] = 1; arr = matrix_pow(arr, n - 2); brr = brr * arr; printf("%d\n", brr.mat[1][1]); } return 0;}
阅读全文
0 0
- 51nod 1126 求递推序列的第N项 (矩阵快速幂)
- 51 nod 1126 求递推序列的第N项(矩阵快速幂)
- 51nod 1126 求递推序列的第N项(矩阵快速幂、循环)
- 51nod 1126 求递推序列的第N项(矩阵快速幂)
- 51nod 1126 求递推序列的第N项 矩阵快速幂
- 51 nod 1126 求递推序列的第N项 矩阵快速幂
- 51nod 1126 求递推序列的第N项【矩阵快速幂】
- 51Nod 1126 求递推序列的第N项 矩阵快速幂
- 51nod 求递推序列的第N项(矩阵快速幂、模拟求循环长度)
- 【51nod 1126】求递推序列的第N项 【矩阵快速幂】or【枚举找循环节】
- 51Nod Problem 1126 求递推序列的第N项(构造矩阵)
- [51NOD]1126 求递推序列的第N项 [线性递推关系与矩阵乘法]
- 1126 求递推序列的第N项(51nod)
- 51nod 1126 求递推序列的第N项
- 51nod 1126 求递推序列的第N项
- 51nod 1126 求递推序列的第N项
- 51nod-【1126 求递推序列的第N项】
- 51Nod 1126 求递推序列的第N项
- Android源码(8) --- Binder(2) 序列化
- 网络编程知识总结 之 简单的iOS HTTP服务器
- 《Android 插件化框架VirtualAPK :(二)原理分析》
- 机器学习精简教程之一——线性代数知识
- 【Machine Learning】笔记:神经网络的表示
- 51nod 1126 求递推序列的第N项 矩阵快速幂
- Android2.2 连接GitHub时出错解决方法
- 线性表的线性存储和链式存储
- eclipse等号左边返回值类型代码自动补全(2017年7月31日19:59:51)
- Android源码(9) --- Binder(3) AIDL使用
- Android Service笔记
- ORB_SLAM2+kinect2+ros_indigo
- Git 命令从入门到转行
- CodeForces