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

来源:互联网 发布:网络发送短信 编辑:程序博客网 时间:2024/05/21 10:05

                            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 <= 1018), You should solve for
g(g(g(n))) mod 109 + 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
012

Sample Output
0142837

Source
2012 ACM/ICPC Asia Regional Chengdu Online

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;}



原创粉丝点击