复杂度为o(n^3logk)
/*
求 a^k % mod,其中a是n*n的矩阵
*/
const int mod = 10000;
const int maxn = 2;
_LL k;
int n;
struct matrix
{
_LL mat[maxn][maxn];
} a,res;
matrix mul(matrix x, matrix y)
{
matrix tmp;
memset(tmp.mat,0,sizeof(tmp.mat));
for(int i = 0; i < n; i++)
{
for(int k = 0; k < n; k++)
{
if(x.mat[i][k] == 0) continue; //小小的优化。
for(int j = 0; j < n; j++)
{
tmp.mat[i][j] += x.mat[i][k] * y.mat[k][j];
if(tmp.mat[i][j] >= mod)
tmp.mat[i][j] %= mod;
}
}
}
return tmp;
}
void solve()
{
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
res.mat[i][j] = (i == j); //初始化为单位矩阵
while(k)
{
if(k & 1)
res = mul(res,a);
a = mul(a,a);
k >>= 1;
}
}
http://poj.org/problem?id=3070
题意:当n非常大时,求斐波那契数列的第n项。矩阵快速幂模板。
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <math.h>
#include <string.h>
#include <queue>
#include <string>
#define LL long long
#define _LL __int64
#define eps 1e-8
using namespace std;
const int mod = 10000;
struct matrix
{
_LL mat[2][2];
}a,res;
_LL k;
int n;
matrix mul(matrix x, matrix y)
{
matrix tmp;
memset(tmp.mat,0,sizeof(tmp.mat));
for(int i = 0; i < n; i++)
{
for(int k = 0; k < n; k++)
{
if(x.mat[i][k] == 0) continue;
for(int j = 0; j < n; j++)
{
tmp.mat[i][j] += x.mat[i][k] * y.mat[k][j];
if(tmp.mat[i][j] >= mod)
tmp.mat[i][j] %= mod;
}
}
}
return tmp;
}
int main()
{
while(~scanf("%I64d",&k))
{
if(k == -1) break;
a.mat[0][0] = a.mat[0][1] = a.mat[1][0] = 1;
a.mat[1][1] = 0;
n = 2;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(i == j) res.mat[i][j] = 1;
else res.mat[i][j] = 0;
}
}
while(k)
{
if(k & 1)
res = mul(res,a);
a = mul(a,a);
k >>= 1;
}
int ans = res.mat[0][1] % mod;
printf("%d\n",ans);
}
return 0;
}