您的位置:首页 > 其它

POJ 3070 Fibonacci 矩阵快速幂

2012-01-23 20:31 405 查看
题意很明确,求第m个斐波那契数MOD10000的结果

题目连矩阵都构造好了,就是

1 1

1 0

然后对这个求幂就行了

/*
ID: sdj22251
PROG: subset
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define MAXN 305
#define INF 100000000
#define eps 1e-7
#define PI 3.1415926535898
using namespace std;
int n = 2, m;
int tt[2][2]={{1, 1}, {1, 0}};
struct wwj
{
int r, c;
int mat[3][3];
} need, ready;
void init()
{
memset(need.mat, 0, sizeof(need.mat));
need.r = n;
need.c = n;
for(int i = 1; i <= n; i++)
{
need.mat[i][i] = 1;
}
ready.c = n;
ready.r = n;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
ready.mat[i][j] = tt[i - 1][j - 1];
}
}
wwj multi(wwj x, wwj y)
{
wwj t;
int i, j, k;
memset(t.mat, 0, sizeof(t.mat));
t.r = x.r;
t.c = y.c;
for(i = 1; i <= x.r; i++)
{
for(k = 1; k <= x.c; k++)
if(x.mat[i][k])
{
for(j = 1; j <= y.c; j++)
{
t.mat[i][j] += (x.mat[i][k] * y.mat[k][j]) % 10000;
t.mat[i][j] %= 10000;
}
}
}
return t;
}
int main()
{
int m;
while(scanf("%d", &m) != EOF)
{
if(m == -1) break;
init();
while(m)
{
if(m & 1)
{
need = multi(ready, need);
}
ready = multi(ready, ready);
m = m >> 1;
}
printf("%d\n", need.mat[1][2] % 10000);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: