题目链接
http://poj.org/problem?id=3070
题意
求斐波那契数列的第N项000
思路 因为 N 是一个非常大的数 如果一步一步 递推 是会T的 如果打表 是会M的
所以采用矩阵快速幂的方法
单位矩阵 为
1 0 0 1
n == 0 的时候 就是 单位矩阵
n == 1 的时候 就是 单位矩阵 * 1 1 1 0 依次类推 a[0][1] 或者 a[1][0] 就是当前项
AC代码
#include <cstdio> #include <cstring> #include <ctype.h> #include <cstdlib> #include <cmath> #include <climits> #include <ctime> #include <iostream> #include <algorithm> #include <deque> #include <vector> #include <queue> #include <string> #include <map> #include <stack> #include <set> #include <numeric> #include <sstream> #include <iomanip> #include <limits> #define CLR(a, b) memset(a, (b), sizeof(a)) #define pb push_back using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef pair<string, int> psi; typedef pair<string, string> pss; const double PI = acos(-1.0); const double E = exp(1.0); const double eps = 1e-8; const int INF = 0x3f3f3f3f; const int maxn = 1e2 + 5; const int MOD = 1e4; struct Matrix { int a[2][2]; Matrix () {} Matrix operator * (Matrix const &b)const { Matrix res; CLR(res.a, 0); for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) res.a[i][j] = (res.a[i][j] + this->a[i][k] * b.a[k][j]) % MOD; return res; } }; Matrix pow_mod(Matrix base, int n) { Matrix ans; CLR(ans.a, 0); for (int i = 0; i < 2; i++) ans.a[i][i] = 1; while (n > 0) { if (n & 1) ans = ans * base; base = base * base; n >>= 1; } return ans; } int main() { Matrix base; base.a[0][0] = base.a[0][1] = base.a[1][0] = 1; base.a[1][1] = 0; int n; while (scanf("%d", &n) && n != -1) { Matrix ans = pow_mod(base, n); cout << ans.a[0][1] << endl; } }转载于:https://www.cnblogs.com/Dup4/p/9433128.html