POJ-3070 矩阵快速幂

POJ-3070

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define MOD 10000
typedef long long LL;
const int maxn = 2;
struct Matrix{
    int m[maxn][maxn];
}ans, res;
 
Matrix mul(Matrix a, Matrix b){
    Matrix tmp;
    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 2; j++){
            tmp.m[i][j] = 0;
        }
    }
    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 2; j++){
            for(int k = 0; k < 2; k++){
                tmp.m[i][j] += ((a.m[i][k] % MOD) * (b.m[k][j] % MOD)) % MOD;
                tmp.m[i][j] %= MOD;
            }
        }
    }
    return tmp;
}
 
void mpoww(int n){
    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 2; j++){
            if(i == j){
                ans.m[i][j] = 1;
            }
            else ans.m[i][j] = 0;
        }
    }
    while(n){
        if(n & 1){
            ans = mul(ans, res);
        }
        res = mul(res, res);
        n >>= 1;
    }
}
 
int main()
{
    int n;
    while(cin >> n && n != -1){
        res.m[0][0] = 1;
        res.m[0][1] = 1;
        res.m[1][0] = 1;
        res.m[1][1] = 0;
        poww(n);
        cout << ans.m[0][1] << endl;
    }
    return 0;
}
发布了54 篇原创文章 · 获赞 28 · 访问量 7299

猜你喜欢

转载自blog.csdn.net/jiangkun0331/article/details/97821582