Another kind of Fibonacci
Time Limit: 3000/1000 MS (Java/others) memory limit: 65536/65536 K (Java/Others)
Total submission (s): 1691 accepted submission (s): 660
Problem descriptionas we all known, the maid Series: F (0) = 1, F (1) = 1, F (n) = f (n-1) + f (n-2) (N> = 2 ). now we define another kind of Fibonacci: A (0) = 1, A (1) = 1, a (n) = x * a (n-1) + y * a (n-2) (N> = 2 ). and we want to calculate S (n), S (n) = a (0) 2 + a (1) 2 + ...... + A (n) 2.
Inputthere are several test cases.
Each test case will contain three integers, n, x, y.
N: 2 <= n <= 231-1
X: 2 <= x <= 231-1
Y: 2 <= Y <= 231-1
Outputfor each test case, output the answer of S (n). If the answer is too big, divide it by 10007 and give me the reminder.
Sample Input
2 1 1 3 2 3
Sample output
6196
It mainly refers to the recursive matrix, and then the rapid power of the matrix:
According to S (n) = S (n-1) + a (n) ^ 2, a (n) ^ 2 = x ^ 2 * a (n-1) ^ 2 + y ^ 2 * a (n-2) ^ 2 + 2 * x * y * a (n-1) * a (n-2), A (n) * a (n-1) = y * a (n-1) * a (n-2) + x * a (n-1) ^ 2, you can construct the following matrix, and then use the binary matrix method to solve the problem.
Recursive Matrix
From: http://www.cnblogs.com/staginner/archive/2012/04/26/2471507.html
Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <algorithm> using namespace STD; const int mod = 10007; struct matrix {long ma [5] [5] ;}; matrix multi (matrix X, matrix Y) // matrix multiplication {matrix ans; memset (ans. ma, 0, sizeof (ans. ma); For (INT I = 1; I <= 4; I ++) {for (Int J = 1; j <= 4; j ++) {If (X. ma [I] [J]) // sparse matrix Optimization for (int K = 1; k <= 4; k ++) {ans. ma [I] [k] = (ans. ma [I] [k] + (X. ma [I] [J] * Y. ma [J] [k]) % mod ;}} retur N ans;} matrix POW (matrix A, long m) {matrix ans; For (INT I = 1; I <= 4; I ++) {for (Int J = 1; j <= 4; j ++) {if (I = J) ans. ma [I] [J] = 1; else ans. ma [I] [J] = 0 ;}while (m) {If (M & 1) ans = multi (ANS, a); A = multi (, a); M = m> 1;} return ans;} int main () {long x, y, N; while (~ Scanf ("% i64d % i64d % i64d", & N, & X, & Y) {matrix A, B; memset (. ma, 0, sizeof (. ma); memset (B. ma, 0, sizeof (B. ma);. ma [1] [1] = 1;. ma [1] [2] = 1;. ma [2] [2] = (x * X) % MOD;. ma [2] [3] = (y * Y) % MOD;. ma [2] [4] = (2 * x * Y) % MOD;. ma [3] [2] = 1;. ma [4] [2] = x;. ma [4] [4] = y; B. ma [1] [1] = 1; B. ma [2] [1] = 1; B. ma [3] [1] = 1; B. ma [4] [1] = 1; A = POW (A, n); A = multi (a, B); printf ("% i64d \ n",. ma [1] [1]);} return 0 ;}
HDU 3306 another kind of Fibonacci (matrix fast power)