[ACM] POJ 3070 Fibonacci (矩阵幂运算)
来源:互联网 发布:淘宝导航栏css编辑器 编辑:程序博客网 时间:2024/06/08 10:41
Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
099999999991000000000-1
Sample Output
0346266875
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
Source
题目中给了提示矩阵。
网赛时才接触矩阵幂运算,自己掌握的知识还是太少了。。。。
代码:
#include <iostream>#include <string.h>#include <stdio.h>#include <algorithm>using namespace std;const int maxn=2;const int mod=10000;int n=2;//矩阵大小int num;//幂大小struct mat{ int arr[maxn][maxn]; mat() { memset(arr,0,sizeof(arr)); }};mat mul(mat a,mat b){ mat ans; for(int i=0;i<n;i++) { for(int k=0;k<n;k++) { if(a.arr[i][k]) for(int j=0;j<n;j++) { ans.arr[i][j]+=a.arr[i][k]*b.arr[k][j]; if(ans.arr[i][j]>=mod) ans.arr[i][j]%=mod; } } } return ans;}mat power(mat p,int k){ if(k==1) return p; mat e; for(int i=0;i<n;i++) e.arr[i][i]=1; if(k==0) return e; while(k) { if(k&1) e=mul(e,p); p=mul(p,p); k>>=1; } return e;}int main(){ mat ori;//题目中的原始矩阵 ori.arr[0][0]=ori.arr[0][1]=ori.arr[1][0]=1; while(cin>>num&&num!=-1) { mat ans; ans=power(ori,num); cout<<ans.arr[0][1]<<endl; } return 0;}
- [ACM] POJ 3070 Fibonacci (矩阵幂运算)
- POJ 3070 Fibonacci (矩阵幂运算)
- poj 3070 Fibonacci(矩阵运算)
- POJ 3070 Fibonacci (矩阵快速幂求fibonacci)
- POJ-3070 Fibonacci(矩阵快速幂求Fibonacci数列)
- poj - 3070 - Fibonacci(矩阵快速幂)
- poj 3070 Fibonacci(矩阵快速幂)
- poj 3070 Fibonacci(矩阵快速幂)
- POJ 3070 Fibonacci(矩阵快速幂)
- 【POJ】3070Fibonacci(矩阵快速幂)
- POJ 3070 Fibonacci(矩阵快速幂)
- POJ 3070 Fibonacci(矩阵快速幂)
- 【POJ 3070】Fibonacci(矩阵快速幂)
- POJ 3070 Fibonacci(矩阵快速幂)
- 【POJ 3070】Fibonacci(矩阵快速幂)
- POJ - 3070 - Fibonacci (矩阵快速幂)
- POJ-3070Fibonacci(矩阵快速幂)
- 【POJ】3070 - Fibonacci(矩阵快速幂)
- Orcad去除修改后元件标号的下划线
- 将Android Studio的快捷键设置与eclipse一致
- 下拉刷新
- 【程序员杂志】创业公司的招人与留人
- Eclipse导入格式化模版
- [ACM] POJ 3070 Fibonacci (矩阵幂运算)
- git 生成 公钥
- 13种排序算法详解(相当清楚,还附有flash动画)
- 反射
- C语言之知识点总结——const指针
- 【笔记】简单易懂的android配置NDK
- 美团2015校招研发笔试题--编程
- 美AFL公司发布光纤连接器检测仪
- windows7 系统游戏全屏显示