【POJ 3070】 Fibonacci

【题目链接】
            点击打开链接
【算法】

          矩阵乘法快速幂
【代码】

           

#include <algorithm>
#include <bitset>
#include <cctype>
#include <cerrno>
#include <clocale>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <limits>
#include <list>
#include <map>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <utility>
#include <vector>
#include <cwchar>
#include <cwctype>
#include <stack>
#include <limits.h>
using namespace std;
const long long MOD = 10000;

long long n;
struct Matrix
{
	long long n,m;
	long long mat[5][5];
} ans;

inline void multipy(Matrix &a,Matrix b)
{
	long long i,j,k;
	Matrix ans;
	ans.n = a.n; ans.m = b.m;
	memset(ans.mat,0,sizeof(ans.mat));
	for (i = 1; i <= a.n; i++)
	{
		for (j = 1; j <= b.m; j++)
		{
			for (k = 1; k <= a.m; k++)
			{
				ans.mat[i][j] = (ans.mat[i][j] + a.mat[i][k] * b.mat[k][j]) % MOD;
			}
		}
	}
	a = ans;
}

inline void power(Matrix &a,long long n)
{
	Matrix p,ans;
	p.n = p.m = 2;
	p.mat[1][1] = 1; p.mat[1][2] = 1;
	p.mat[2][1] = 1; p.mat[2][2] = 0;
	ans.n = ans.m = 2;
	ans.mat[1][1] = 1; ans.mat[1][2] = 0;
	ans.mat[2][1] = 0; ans.mat[2][2] = 1;
	while (n > 0)
	{
		if (n & 1) multipy(ans,p);
		n >>= 1;
		multipy(p,p);	
	}
	a = ans;
}

inline void solve()
{
	Matrix tmp; 
	tmp.n = 2; tmp.m = 1;
	tmp.mat[1][1] = 1; tmp.mat[2][1] = 0;
	ans.n = ans.m = 2;
	ans.mat[1][1] = ans.mat[1][2] = ans.mat[2][1] = 1;
	ans.mat[2][2] = 0;
	power(ans,n-1);
	multipy(ans,tmp);	
	cout<< ans.mat[1][1] << endl;
}

int main()
{
	
	while (scanf("%lld",&n) != EOF && n != -1)
	{
		if (!n) cout<< 0 << endl;
		else if (n == 1) cout<< 1 << endl;
		else solve();	
	}
	
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值