矩阵快速幂求fibonacci数。
思路:因为上次周赛遇到一道求fibonacci的变形题,那个数与fibonacci的关系都推出来了,但是由于数据量有1000,各种超unsigned long long ,一直TLE,所以今天从师兄给我的矩阵资料上找到矩阵快速幂求fibonacci数的资料。待会同学过生日去吃饭,回来再写写总结。
这篇文章写的蛮不错的:http://www.cnblogs.com/Knuth/archive/2009/09/04/1559951.html
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int MOD = 10000;
int n;
void Mul(int d[][2], int a[][2], int b[][2], int n)
{
int c[2][2];
memset(c, 0, sizeof(c));
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
int tot = 0;
for(int k = 0; k < n; k++)
{
tot += a[i][k] * b[k][j];
if(tot >= MOD) tot %= MOD;
}
c[i][j] = tot;
}
}
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
d[i][j] = c[i][j];
}
}
}
int cal(int n)
{
int t[2][2] = {{0, 1}, {0, 1}};
int a[2][2] = {{0, 1}, {1, 1}};
while(n)
{
if(n & 1) Mul(t, t, a, 2);
Mul(a, a, a, 2);
n /= 2;
}
return t[0][0];
}
int read_case()
{
scanf("%d", &n);
if(n == -1) return 0;
return 1;
}
void solve()
{
if(!n) { printf("0\n"); return ;}
int ans = cal(n);
printf("%d\n", ans);
}
int main()
{
while(read_case())
{
solve();
}
return 0;
}