POJ ~ 3070 ~ Fibonacci （矩阵快速幂模板）

//#include <bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const int MOD = 1e4;
struct mat
{
int r, c;
ll m[10][10];

mat (int r, int c)
{
this->r = r, this->c = c;
memset(m, 0, sizeof(m));
}

mat operator + (mat a) const
{
mat ans(r, c);
for (int i = 1; i <= r; i++)
{
for (int j = 1; j <= c; j++)
{
ans.m[i][j] = (m[i][j] + a.m[i][j]) % MOD;
}
}
return ans;
}

mat operator * (mat a) const
{
mat tmp(r, a.c);
for (int i = 1; i <= tmp.r; i++)
{
for (int j = 1; j <= tmp.c; j++)
{
tmp.m[i][j] = 0;
for (int k = 1; k <= c; k++)
{
tmp.m[i][j] = (tmp.m[i][j] + (m[i][k] * a.m[k][j]) % MOD) % MOD;
}
}
}
return tmp;
}

mat operator ^ (int n) const //注意运算符优先级比较低，多用括号；
{
mat ans(r, r), tmp(r, r);
memcpy(tmp.m, m, sizeof(tmp.m));
for (int i = 1; i <= ans.r; i++) ans.m[i][i] = 1;
while(n)
{
if(n&1) ans = ans*tmp;
tmp = tmp*tmp;
n >>= 1;
}
return ans;
}

void print() const
{
for (int i = 1; i <= r; i++)
{
for (int j = 1; j <= c; j++)
{
printf("%lld",m[i][j]);
if (j == c) printf("\n");
else printf(" ");
}
}
}

};
int main()
{
int n;
while (cin >> n && (n != -1))
{
mat A(3, 3);
A.m[1][1] = 1; A.m[1][2] = 1;
A.m[2][1] = 1; A.m[2][2] = 0;
A = (A^n);
cout << A.m[2][1] << endl;
}
return 0;
}
/*
0
9
999999999
1000000000
-1
*/