Number Sequence(HDU 1005 构造矩阵 )
2016-05-06 11:44
411 查看
Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 147964 Accepted Submission(s): 35964
[align=left]Problem Description[/align]
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).
[align=left]Sample Input[/align]
1 1 3
1 2 1
0
0 0 0
[align=left]Sample Output[/align]
2
5
因为数据量比较大,可以打表找到循环规律,但这种类型的题发现都可以构造矩阵求解
f
= a b * f[n-1]
f[n-1] 1 0 f[n-2]
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; int a,b,n; int m[1000]; struct Matrix { int mat[2][2]; }p; Matrix mul(Matrix a,Matrix b) { Matrix c; for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { c.mat[i][j]=0; for(int k=0;k<2;k++) c.mat[i][j]=(c.mat[i][j]+a.mat[i][k]*b.mat[k][j])%7; } } return c; } Matrix mod_pow(Matrix x,int n) { Matrix res; memset(res.mat,0,sizeof(res.mat)); for(int i=0;i<2;i++) res.mat[i][i]=1; while(n) { if(n&1) res=mul(res,x); x=mul(x,x); n>>=1; } return res; } int main() { freopen("in.txt","r",stdin); while(scanf("%d%d%d",&a,&b,&n)!=EOF) { if(a==0&&b==0&&n==0) break; if(n<2) { printf("1\n"); continue; } p.mat[0][0]=a; p.mat[1][0]=1; p.mat[0][1]=b; p.mat[1][1]=0; Matrix ans= mod_pow(p,n-2); printf("%d\n",(ans.mat[0][0]+ans.mat[0][1])%7); } }
相关文章推荐
- ios中获得UUID的方法,ios怎么获得uuid
- Intellij Idea 12 生成serialVersionUID的方法
- 让UITableView的表头随着tableView一起滚动
- 动态获取UILabel的bounds
- UITableView设置单元格选中后只显示一个打勾的三种简单方法(仅供参考)
- UITableView设置单元格选中后只显示一个打勾的三种简单方法(仅供参考)
- ios学习笔记之UIView
- Android UI性能优化实战 识别绘制中的性能问题
- UITextField左侧的表达图片(..我也不知道叫什么)
- DelayQueue的原理和使用浅谈
- Leetcode 303 Range Sum Query - Immutable
- UE4 下载4.11.2的时候:当前遇到连接问题,正在重试
- chmod命令高级篇( SetUID与SetGID标识位)
- UITextField的使用总结
- codeforces 670E. Correct Bracket Sequence Editor
- android线程间通信和主线程更新ui
- UIRectEdgeNone
- MP 新版本 [2 mysql sequelize 搭建数据库]
- PriorityBlockingQueue详解
- Request获取url各种信息的方法