HDU4291 循环节+矩阵连乘2012 ACM/ICPC Asia Regional Chengdu Online1004

                            A Short problem

                                               Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
                                                           Total Submission(s): 404 Accepted Submission(s): 165


Problem Description
  According to a research, VIM users tend to have shorter fingers, compared with Emacs users.
  Hence they prefer problems short, too. Here is a short one:
  Given n (1 <= n <= 10 18), You should solve for
g(g(g(n))) mod 10 9 + 7

  where
g(n) = 3g(n - 1) + g(n - 2)

g(1) = 1

g(0) = 0


Input
  There are several test cases. For each test case there is an integer n in a single line.
  Please process until EOF (End Of File).

Output
  For each test case, please print a single line with a integer, the corresponding answer to this case.

Sample Input
  
  
0 1 2

Sample Output
  
  
0 1 42837

Source

Recommend
liuyiding


题解:这题需要考虑循环节 然后利用矩阵连乘 相对比于其他的广义斐波那契问题 这题给了好几层斐波那契数来取余 这就很麻烦了 首先通过
暴力 找出g(n)mod10^9+7的循环节 循环节的值为222222224 就是g(g(n))达到222222224的时候222222225时g(222222225)%10^9+7的值
为0 222222226的值为1.... 再次通过暴力 求出g(g(n))循环节的值为183120 同理 再求一次就是240 也就是n的循环节 n经过240循环一次 
然后通过矩阵连乘 快速幂取余 模板就可以过掉 scanf会WA 所以用cin 
注意不要用矩阵连乘找循环节 知道多慢吗 慢到我以为这题没循环节 哎 如果昨天脑子好用 用暴力求了 这题我就过了

#include <iostream>
#include<cstdio>
#include<cmath>

using namespace std;

const int MAX = 2;
int M;
typedef  struct
{
    long long m[MAX][MAX];
}  Matrix;

Matrix P =
{
    0,1,
    1,3,
};

Matrix I = {1,0,
            0,1,
           };

Matrix matrixmul(Matrix a,Matrix b) //矩阵乘法
{
    int i,j,k;
    Matrix c;
    for (i = 0 ; i < MAX; i++)
        for (j = 0; j < MAX; j++)
        {
            c.m[i][j] = 0;
            for (k = 0; k < MAX; k++)
                c.m[i][j] += (a.m[i][k] * b.m[k][j])%M;
            c.m[i][j] %= M;
        }
    return c;
}

Matrix quickpow(long long n)
{
    Matrix m = P, b = I;
    while (n >= 1)
    {
        if (n & 1)
            b = matrixmul(b,m);
        n = n >> 1;
        m = matrixmul(m,m);
    }
    return b;
}

int main()
{
    long long n,m,c,b;
    while(cin>>n)
    {
        n%=240;
        M=183120;
        m=quickpow(n).m[0][1]%M;
        M=222222224;
        m=quickpow(m).m[0][1]%M;
        M=1000000007;
        m=quickpow(m).m[0][1]%M;
        cout<<m<<endl;
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值