NYOJ 148 矩阵快速幂模版
2015-05-02 10:01
369 查看
矩阵快速幂,其实就是和快速幂的原理相同的, 只是把两个矩阵相乘。
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int N = 2; const int mod = 10000; struct Node { int row, cal; int s ; Node ()//需要构造的矩阵 { row = cal = N; s[0][0] = 1, s[0][1] = 1; s[1][0] = 1, s[1][1] = 0; } }; Node Matble(Node x, Node y)//矩阵的乘法 { Node ans; ans.row = x.row; ans.cal = y.cal; for(int i = 0; i < ans.row; i++) for(int j = 0; j < ans.cal; j++) ans.s[i][j] = 0; for(int i = 0; i < ans.row; i++)//两个矩阵相乘 for(int j = 0; j < ans.cal; j++) for(int k = 0; k < x.cal; k++) ans.s[i][j] = (int)(ans.s[i][j] + (long long)x.s[i][k] * y.s[k][j] % mod) % mod;//技巧,相乘可能超int return ans; } int pow_Matble(int n) //快速幂 { if(!n) return 0; Node ans, temp; ans.s[0][0] = 1, ans.s[0][1] = 0; ans.s[1][0] = 0, ans.s[1][1] = 1; while(n > 0) { if(n&1) ans = Matble(ans, temp);//改成矩阵相乘 temp = Matble(temp, temp);//改成矩阵相乘 n /= 2; } return ans.s[0][1];//返回矩阵中我们需要的结果 } int main() { int n; while(scanf("%d", &n), n >= 0) printf("%d\n", pow_Matble(n)); return 0; }
相关文章推荐
- NYOJ 题目148 fibonacci数列(二)(矩阵快速幂)
- nyoj--148 fibonacci数列(二)(矩阵快速幂)
- nyoj 148 fibonacci数列(二)(矩阵快速幂)
- nyoj 148 fibonacci数列(二) 【矩阵快速幂】
- NYOJ 148 fibonacci数列(二)【矩阵快速幂】
- nyoj_148_fibonacci数列(二)_矩阵快速幂
- hdu2276-nyoj300矩阵快速幂
- nyoj 301 递推求值(矩阵快速幂)
- 【矩阵快速幂】 hdu5667 Sequence 、nyoj1000 又见斐波那契数列
- Hdu 2276 && Nyoj 300 Kiki & Little Kiki 2[矩阵快速幂]
- NYOJ 301 递推求值【矩阵快速幂取模】
- nyoj 301 递推求值(矩阵快速幂)
- poj 3734 <矩阵快速幂模版>
- 模版—矩阵连乘快速幂
- nyoj fibonacci数列(二) 148 (矩阵快速幂模板)
- POJ 3233 && NYOJ 298 Matrix Power Series(矩阵快速幂)
- nyoj 301 递推求值(矩阵快速幂)
- NYOJ301递推求值 NYOJ 1000又见斐波那契数列(矩阵快速幂)
- nyoj 301 递推求值(矩阵快速幂)
- 【矩阵快速幂】POJ 3233 && NYOJ 298 Matrix Power Series