矩阵快速幂——poj 3070求斐波那契数列

在这里插入图片描述第一次提交maxn设置成3,错误,设置成2即可

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<vector>
#include<string>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int maxn = 2;
const int mod = 10000;

ll n;
struct mat{         //用结构体存矩阵
    ll m[maxn][maxn];
}unit;

void init_unit(){       //单位矩阵
    for(int i=0; i<maxn; i++)
        unit.m[i][i] = 1;
    return ;
};

mat operator *(mat a, mat b){          //重新定义乘法
    mat ret;
    for(int i=0; i<maxn; i++)       //!!注意是到maxn,写成n就错
        for(int j=0; j<maxn; j++){
            ll sum = 0;
            for(int k=0; k<maxn; k++)
                sum += a.m[i][k] * b.m[k][j] % mod;
            ret.m[i][j] = sum % mod;
        }
    return ret;
}

mat pow_mat(mat a,ll n){       //矩阵快速幂
    mat ret = unit;
    while(n){
        if(n&1) ret = ret * a;
        a = a*a;
        n >>= 1;
    }
    return ret;
}

int main(){
    while(cin >> n && n!=-1){
        if(n==0){
            cout << 0 << endl;
            continue;
        }
        init_unit();
        mat a;
        a.m[0][0] = a.m[0][1] = a.m[1][0] = 1;
        a.m[1][1] = 0;
        a = pow_mat(a,n);
        cout << a.m[0][1] % mod << endl;
    }
    return 0;
}

发布了31 篇原创文章 · 获赞 0 · 访问量 928

猜你喜欢

转载自blog.csdn.net/jhckii/article/details/104273400