poj 3070 Fibonacci 【矩阵乘法】
http://poj.org/problem?id=3070
题目大意:用矩阵乘法求Fibonacci数列
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <cmath> #include <queue> using namespace std; template <class T> void checkmin(T &t,T x) {if(x < t) t = x;} template <class T> void checkmax(T &t,T x) {if(x > t) t = x;} template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;} template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;} typedef pair <int,int> PII; typedef pair <double,double> PDD; typedef long long ll; #define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++) const int N = 2; int n , MOD; struct Matrix { int n , m; int a[N][N]; Matrix() {} Matrix(int _n,int _m):n(_n),m(_m){}; void intput() { for(int i=0;i<n;i++) for(int j=0;j<m;j++) scanf("%d",&a[i][j]); } Matrix operator + (const Matrix &b) { Matrix tmp = Matrix(n,m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) tmp.a[i][j] = a[i][j] + b.a[i][j]; return tmp; } Matrix operator - (const Matrix &b) { Matrix tmp = Matrix(n,m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) tmp.a[i][j] = a[i][j] - b.a[i][j]; return tmp; } Matrix operator * (const Matrix &b) { Matrix tmp = Matrix(n,b.m); for(int i=0;i<n;i++) for(int j=0;j<b.m;j++) tmp.a[i][j] = 0; for(int i=0;i<n;i++) for(int j=0;j<b.m;j++) for(int k=0;k<m;k++) { tmp.a[i][j] += a[i][k]*b.a[k][j]; tmp.a[i][j] %= MOD; } return tmp; } }; Matrix operator ^ (Matrix a , int p) { Matrix ret = Matrix(a.n,a.m); for(int i=0;i<a.n;i++) for(int j=0;j<a.m;j++) ret.a[i][j] = (i == j ? 1 : 0); while(p) { if(p%2) ret = ret * a; a = a * a; p /= 2; } return ret; } /* Matrix mi(Matrix a , int p) { Matrix tmp = Matrix(a.n,a.m); for(int i=0;i<a.n;i++) for(int j=0;j<a.m;j++) if(i==j) tmp.a[i][j]=1; else tmp.a[i][j]=0; if(p == 0) return tmp; if(p == 1) return a; if(p % 2) tmp = a; Matrix tt = mi(a , p/2); return tt * tt * tmp; }*/ Matrix A; int main() { MOD = 10000; while(~scanf("%d",&n) && n != -1) { A = Matrix(2,2); A.a[0][0] = A.a[0][1] = A.a[1][0] = 1; A.a[1][1] = 0; //A = mi(A,n); A = A^n; printf("%d\n" , A.a[1][0]); /* cout << "n is "<<nn <<endl; cout << "check" << endl; for(int i=0;i<A.n;i++) { for(int j=0;j<A.m;j++) cout << A.a[i][j] << " "; cout << endl; } */ } return 0; }