ZOJ 2105 Number Sequence(矩阵快速幂)
2015-07-31 16:23
417 查看
注: 第一想法就是矩阵快速幂,还有一想法是maybe有规律可循,这里用的是矩阵快速幂解法
Number Sequence
Time Limit: 2 Seconds Memory Limit: 65536 KB
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).
构建矩阵:(矩阵竖线没那么长,将就看下吧)
发现规律了吧,矩阵快速幂模板
Number Sequence
Time Limit: 2 Seconds Memory Limit: 65536 KB
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).
构建矩阵:(矩阵竖线没那么长,将就看下吧)
发现规律了吧,矩阵快速幂模板
#include<iostream> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<queue> #include<stack> #include<cstdlib> #include<cstdio> #include<set> #include<map> #define N 2 #define mod 7 typedef long long LL; using namespace std; struct Mar{ int a ; void init(){ for(int i=0;i<2;i++) a[i][i]=1; } void zero(){ memset(a,0,sizeof(a)); } }; Mar operator * (const Mar x,const Mar y){ Mar t; t.zero(); for(int k=0;k<2;k++){ for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ t.a[i][j]+=x.a[i][k]*y.a[k][j]; t.a[i][j]%=mod; } } } return t; } Mar operator ^ (Mar x,int n){ Mar t; t.zero(); t.init(); while(n){ if(n%2==1) t=t*x; x=x*x; n/=2; } return t; } int main(){ int n,a,b,ans; Mar t; while(scanf("%d%d%d",&a,&b,&n)!=EOF){ if(!n&&!a&&!b) break; if(n==1) ans=1; else if(n==2) ans=1; else{ t.a[0][0]=a,t.a[0][1]=1,t.a[1][0]=b,t.a[1][1]=0; t = t^(n-2); ans=t.a[0][0]+t.a[1][0]; } printf("%d\n",ans%mod); } return 0; }
相关文章推荐
- 提高android应用ui运行效率
- Error:Cannot build Artifact :war exploded because it is included into a circular depency
- iOS阶段学习第30天笔记( UIViewController—Delegate(代理) )
- (转)UIViewController中各方法调用顺序及功能详解
- hdu 4396 More lumber is required(最短路)
- [leetcode] Implement Stack using Queues
- UIView常用的一些方法小记之setNeedsDisplay和setNeedsLayout
- break和continue
- UI控件---CollectionView
- MenuInflater用法
- 设置UITableviewCell的separatorStyle左边顶格
- easyui combogrid 的查询
- 响应式web设计之CSS3 Media Queries
- Target runtime com.genuitec.runtime.generic.jee50 is not defined
- ue怎样取消保存生成的.bak文件
- HDOJ 题目4339 Query(线段树,单点更新)
- ubuntu-64位 error while loading shared libraries: libuuid.so.1: wrong ELF class: ELFCLASS64
- iOS开发 扩大UIButton的响应区域
- measure_circuit_width_lines_gauss.hdev检测pcb线宽 相关例程学习
- requireJs详解(二)