poj3070 Fibonacci ——矩阵快速幂
May 19, 2013
POJ
Math
题目链接:http://poj.org/problem?id=3070 题目大意: 求第N项的Fibonacci数的后四位。 题目思路: 根据公式: 用矩阵快速幂就OK,模板题……但还是TLE了一次,原因是题目要求输入-1结束,我没看到……o(╯□╰)o
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAX = 2;
const int M = 10000;
typedef struct {
int m[MAX][MAX];
}Matrix;
Matrix a, per;
int n;
void init() {
int i , j;
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
per.m[i][j] = (i == j);
}
}
a.m[0][0] = a.m[0][1] = a.m[1][0] = 1; a.m[1][1] = 0;
}
Matrix multi(Matrix a, Matrix b) {
Matrix c;
int k, i, j;
for ( i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
c.m[i][j] = 0;
for (k = 0; k < n; ++k) {
c.m[i][j] += a.m[i][k] * b.m[k][j];
}
c.m[i][j] %= M;
}
}
return c;
}
Matrix power(int k) {
Matrix p, ans = per;
p = a;
while (k) {
if (k & 1) {
ans = multi(ans, p); k--;
}
else {
k /= 2; p = multi(p, p);
}
}
return ans;
}
int main(void) {
Matrix ans; int k; n = 2;
init();
while (~scanf("%d", &k)) {
if (k == -1) break;
init();
ans = power(k);
printf("%d\n", ans.m[1][0]);
}
return 0;
}
其实就是完完全全的模板……