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 Descriptiona 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 is to calculate the value of f (n).
Inputthe input consists of multiple test cases. Each test case contains 3 integers a, b and N in a single line (1 <= A, b <=, 1 <= n <= 100,000,000). Three zeros signal the end of the input and this test case are not a is processed.
Outputfor each test case, print the value of f (n) in a single line.
Sample INPUT1 1 31 2 100 0 0
Sample Output25
Recently learned a simple two-dimensional matrix fast power, found very useful. So I looked for a recursive question that I had done before. Most people are supposed to be violent. The table finds the first 49 items of the cyclic section rule, but it is also suitable for using matrices to speed up the need for an item. As long as the matrix or determinant multiplication is possible. In addition, in order to write the natural beauty of the function changed to the operator overload.
(The matrix can be written in many ways, f1,f2 position, cross-write or even more outrageous), as long as the correct results can be obtained.
If you find the recursive type after just pay attention to whether the index should be N or n-1 or n-2, and then a slightly special sentence, the other should be no problem.
#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 0x3f3f3f3fstruct 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 (i NT 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;}
Hdu--1005number Sequence (template problem two-dimensional matrix fast Power + operator overloading)