您的位置:首页 > 其它

矩阵快速幂 POJ 3070 Fibonacci

2015-07-31 20:34 381 查看
题目传送门

 /*
矩阵快速幂:求第n项的Fibonacci数,转置矩阵都给出,套个模板就可以了。效率很高啊
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;

const int MAXN = 1e3 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 10000;
struct Mat   {
int m[2][2];
};

Mat multi_mod(Mat a, Mat b)   {
Mat ret;    memset (ret.m, 0, sizeof (ret.m));
for (int i=0; i<2; ++i) {
for (int j=0; j<2; ++j) {
for (int k=0; k<2; ++k) {
ret.m[i][j] = (ret.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
}
}
}
return ret;
}

int matrix_pow_mod(Mat x, int n)   {
Mat ret; ret.m[0][0] = ret.m[1][1] = 1;  ret.m[0][1] = ret.m[1][0] = 0;
while (n)   {
if (n & 1)  ret = multi_mod (ret, x);
x = multi_mod (x, x);
n >>= 1;
}
return ret.m[0][1];
}

int main(void)  {       //POJ 3070 Fibonacci
int n;
while (scanf ("%d", &n) == 1)   {
if (n == -1)    break;
Mat x;
x.m[0][0] = x.m[0][1] = x.m[1][0] = 1; x.m[1][1] = 0;
printf ("%d\n", matrix_pow_mod (x, n));
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: