码迷,mamicode.com
首页 > 其他好文 > 详细

Hdu2855Fibonacci Check-up矩阵

时间:2014-10-30 20:47:17      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   for   sp   div   

转个图。

bubuko.com,布布扣

或者打表找的规律是  g[n] = 3*g[n-1] - g[n-2];

构造个 3 -1  的矩阵然后搞下就好了。

         1  0  

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <string.h>
typedef long long LL;
using namespace std;

LL mod;

struct Matrix
{
    LL m[4][4];
};

Matrix Mul(Matrix a, Matrix b)
{
    Matrix ans;
    for (LL i = 0; i < 2; i++){
        for (LL j = 0; j < 2; j++){
            ans.m[i][j] = 0;
            for (LL k = 0; k < 2; k++)
                ans.m[i][j] += a.m[i][k] * b.m[k][j], ans.m[i][j] = (ans.m[i][j] + mod) % mod;
        }
    }
    return ans;
}

Matrix quick(Matrix a, LL b)
{
    Matrix ans;
    for (LL i = 0; i < 2; i++)
    for (LL j = 0; j < 2; j++)
        ans.m[i][j] = (i == j);
    Matrix c;
    c = Mul(a, a);
    while (b){
        if (b & 1) ans = Mul(a, ans);
        a = Mul(a, a);
        b >>= 1;
    }
    return ans;
}

Matrix init()
{
    Matrix ans;
    ans.m[0][0] = 3; ans.m[0][1] = -1;
    ans.m[1][0] = 1; ans.m[1][1] = 0;
    return ans;
}
int main()
{
    LL T;
    LL n;
    cin >> T;
    while (T--){
        cin >> n >> mod;
        if (n == 0){
            cout << 0 << endl; continue;
        }
        if (n == 1){
            cout << 1 << endl; continue;
        }
        Matrix ans = init();
        ans = quick(ans, n - 1);
        cout << ans.m[0][0] << endl;
    }
    return 0;
}

 

Hdu2855Fibonacci Check-up矩阵

标签:style   blog   http   io   color   os   for   sp   div   

原文地址:http://www.cnblogs.com/yigexigua/p/4063560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!