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).
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; }