HDU 1005 Number Sequence 矩阵乘法 Fib数列
来源:互联网 发布:sql2005数据库无法访问 编辑:程序博客网 时间:2024/05/08 03:56
原题: http://acm.hdu.edu.cn/showproblem.php?pid=1005
题目:
Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 128931 Accepted Submission(s): 31368
Problem Description
A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
0 0 0
Sample Output
2
5
思路:
按规律求出第n项。
由矩阵乘法我们可以知道:
所以对于fib数列我们可以用矩阵来求,由于矩阵可以左乘右乘,所以我们可以用快速幂来优化。
代码:
#include<iostream>#include"string.h"#include<stdio.h>using namespace std;const int bc=2;const int mod = 7;struct matrix{ int x[bc][bc];};matrix mutimatrix(matrix a,matrix b){ matrix temp; memset(temp.x,0,sizeof(temp.x)); for(int i=0;i<bc;i++) //答案的行 { for(int j=0;j<bc;j++) //答案的列 { for(int k=0;k<bc;k++) { temp.x[i][j]+=a.x[i][k]*b.x[k][j]; temp.x[i][j]%=mod; } } } return temp;}matrix powmatrix(matrix a,int b){ matrix temp; memset(temp.x,0,sizeof(temp.x)); //初始化矩阵为单位阵 for(int i=0;i<bc;i++) temp.x[i][i]=1; while(b) { if(b%2==1) temp=mutimatrix(temp,a); a=mutimatrix(a,a); b=b/2; } return temp;}int main(){ int a,b,n; //freopen("in.txt","r",stdin); while(scanf("%d %d %d",&a,&b,&n)!=EOF) { if(a==0&&b==0&&n==0) break; matrix st; //因为每次都是a个F(n-1)和b个F(n-2)相加,所以这里如此初始化 //Fib数列这里就直接单位阵 st.x[0][0]=a; st.x[0][1]=1; st.x[1][0]=b; st.x[1][1]=0; st=powmatrix(st,n-1); printf("%d\n",(st.x[0][1]+st.x[1][1])%mod); } return 0;}
- HDU 1005 Number Sequence 矩阵乘法 Fib数列
- hdu 1005 Number Sequence 矩阵乘法
- hdu 3936 FIB Query 菲波拉切数列的性质+矩阵乘法
- Number Sequence hdu 构造矩阵乘法
- UVA 10689 Yet another Number Sequence(矩阵快速幂求Fib数列)
- HDU-1005 Number Sequence【矩阵二分幂】
- Hdu 1005 Number Sequence//矩阵快速幂
- hdu 1005 Number Sequence 矩阵基础题
- HDU 1005 Number Sequence(矩阵快速幂)
- HDU-1005- Number Sequence (矩阵快速幂)
- HDU 1005 Number Sequence 矩阵快速幂
- hdu 1005 Number Sequence 构造矩阵 + 矩阵快速幂
- [HDU 5950]Recursive sequence:矩阵乘法
- HDU-5950 Recursive sequence(矩阵乘法)
- hdu 1005Number Sequence (矩阵快速幂)
- HDU-#1005 Number Sequence(矩阵二分幂)
- HDU 1005 Number Sequence(矩阵快速幂)
- HDU 1005 Number Sequence(基础矩阵快速幂)
- LeetCode Add Two Numbers 空头节点
- 数据类型的理解
- 获取SQLSERVER 表结构信息
- RTC驱动
- 西普学院 writeup 逆向工程 该题不简单
- HDU 1005 Number Sequence 矩阵乘法 Fib数列
- 使用surface显示yuv数据
- 谁是最强的女汉子
- oracle数据库序列号自增
- C++ 手动替换malloc函数,并且手动获取调用者地址
- 排序算法
- MySQL添加字段和修改字段的方法
- Android将程序崩溃信息保存本地文件
- javascript执行顺序