Number Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 148003    Accepted Submission(s): 35976

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

最近学了简单一点的二维的矩阵快速幂,发现十分好用。于是又找以前做过的递推式的题目。大部分人做法应该是暴力打表发现循环节规律取前49项即可,但是这题也很适合用矩阵来加速求需要的某一项。只要会矩阵或者行列式的乘法就可以。另外为了写起来自然美观把函数改成了操作符重载。

(矩阵写法可以有很多种,F1,F2位置互换、横着写或者更离谱也行,只要能得出正确结果即可)

若求出递推式后只要注意一下指数到底应该是n还是n-1还是n-2,然后稍微特判一下,其他应该没啥问题。

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef long long LL;
#define INF 0x3f3f3f3f
struct mat
{
int pos[2][2];
mat(){memset(pos,0,sizeof(pos));}
};
inline mat operator*(const mat &a,const mat &b)
{
mat c;
for (int i=0; i<2; i++)
{
for (int j=0; j<2; j++)
{
for (int k=0; k<2; k++)
{
c.pos[i][j]+=(a.pos[i][k]*b.pos[k][j])%7;
}
}
}
return c;
}
inline mat operator^(mat a,LL b)
{
mat r;r.pos[0][0]=r.pos[1][1]=1;
mat bas=a;
while (b!=0)
{
if(b&1)
r=r*bas;
bas=bas*bas;
b>>=1;
}
return r;
}
int main(void)
{
ios::sync_with_stdio(false);
int n,a,b;
while (cin>>a>>b>>n&&(a||b||n))
{
if(n==1)
{
cout<<1<<endl;
continue;
}
mat one,t;
one.pos[0][0]=one.pos[1][0]=1;
t.pos[0][0]=a,t.pos[0][1]=b;t.pos[1][0]=1;
t=t^(n-2);
one=t*one;
cout<<one.pos[0][0]%7<<endl;
}
return 0;
}

最新文章

  1. 【DP】HDU 1260
  2. Spring配置文件中使用表达式
  3. git入门学习(二):新建分支/上传代码/删除分支
  4. 二:Go编程语言规范-类型
  5. python安装paramiko模块
  6. php导出excel
  7. 制作越狱版本的ipa文件
  8. css去掉a标签点击后的虚线框(转自网络)
  9. Commons Lang - StringUtils
  10. jedis源码阅读
  11. 学习生命周期activity
  12. 结对作业-基于GUI的四则运算
  13. 学习札记 ----wind7下如何安装SqlServer数据库
  14. Unity3D input.GetAxis
  15. Wcf传递的参数实际不为空,但是接收时显示为空。
  16. day 25 二十五、抽象类、多态、鸭子、反射、异常处理
  17. iOS开发-命令模式
  18. SQLSERVER 2012 之 “代理 XP”组件已作为此服务器安全配置的一部分被关闭
  19. 和我一起学Effective Java之泛型
  20. Ubuntu16.04开机蓝屏问题解决

热门文章

  1. Android(java)学习笔记107:Relativelayout相对布局
  2. 一、git提交代码步骤
  3. git clone 和 download 不一样,能用git clone 就用git clone,download的代码,经常出现安装bug
  4. Google 出品的 Java 编码规范,强烈推荐,权威又科学!
  5. Java获取yml里面的配置
  6. (69)zabbix监控惠普打印机
  7. CSS基础(一)
  8. 老男孩Python高级全栈开发工程师三期完整无加密带课件(共104天)
  9. Linux中断体系结构
  10. MySQL迁移至MariaDB