Contemplation! Algebra 矩阵快速幂
Posted joeylee97
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Contemplation! Algebra 矩阵快速幂相关的知识,希望对你有一定的参考价值。
Given the value of a+b and ab you will have to find the value of a n + b n Input The input file contains several lines of inputs. Each line except the last line contains 3 non-negative integers p, q and n. Here p denotes the value of a+b and q denotes the value of ab. Input is terminated by a line containing only two zeroes. This line should not be processed. Each number in the input file fits in a signed 32-bit integer. There will be no such input so that you have to find the value of 00 . Output For each line of input except the last one produce one line of output. This line contains the value of a n + b n. You can always assume that a n + b n fits in a signed 64-bit integer.
Sample Input
10 16 2 7 12 3 0 0
Sample Output
68 91
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<algorithm> #include<queue> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 49 #define MOD 10000007 #define INF 1000000009 const double eps = 1e-9; /* 矩阵快速幂! an = p an - q an-1 */ LL p, q, n; struct Mat { Mat() { memset(a, 0, sizeof(a)); } LL a[2][2]; Mat operator * (const Mat& rhs) { Mat ret; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (a[i][j]) { for (int k = 0; k < 2; k++) ret.a[i][k] += a[i][j] * rhs.a[j][k]; } } } return ret; } }; Mat fpow(Mat m, LL b) { Mat tmp = m, ans; ans.a[1][1] = ans.a[0][0] = 1; while (b != 0) { if (b & 1) ans = tmp * ans; tmp = tmp * tmp; b /= 2; } return ans; } int main() { while (scanf("%lld%lld%lld", &p, &q, &n) == 3) { LL a1 = p, a2 = p*p - 2 * q; if (n == 0) printf("2\n"); else if (n == 1) printf("%lld\n", a1); else if (n == 2) printf("%lld\n", a2); else { n = n - 2; Mat M; M.a[0][0] = p, M.a[0][1] = -q, M.a[1][0] = 1; M = fpow(M, n); printf("%lld\n", M.a[0][0] * a2 + M.a[0][1] * a1); } } }
以上是关于Contemplation! Algebra 矩阵快速幂的主要内容,如果未能解决你的问题,请参考以下文章
UVa 10655 Contemplation! Algebra 矩阵快速幂