# A Short problem【矩阵快速幂+循环节】

A Short problem

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

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
0
1
2

Sample Output
0
1
42837

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef long long ll;
int n;
ll u;
ll MOD = 1000000007;
ll k[3]= {183120, 222222224, 1000000007};//每次的取余，循环节
//据金桔所说，线性的规律循环节通常是跑到头：
//ll a = 0, b = 1;
//for(ll i=3;;i++)
//{
//    ll c= 3*a+b;
//    a  = b;
//    b = c;
//    if(a==0&&b==1)//因为线性终会跑到头
//    {
//        cout<<i<<endl;//循环节
//        break;
//    }
//}//跑完之后的答案就是之前的一个要取模的数，把这个数字赋值给MOD，然后再跑，就找到了第二个……
struct mat
{
ll m[4][4];
} init, q;
ll mod(ll x)
{
return (x+MOD)%MOD;
}
void init_mat()
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
init.m[i][j] = 0;
q.m[i][j] = 0;
}
}
}

mat operator *(mat a, mat b)
{
mat ret;
ll x;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
x = 0;
for(int k=0; k<n; k++)
{
x += mod((ll)(a.m[i][k]*b.m[k][j]));
x %=MOD;
}
ret.m[i][j] = x;
}
}
return ret;
}

mat mat_pow(mat a, ll x)
{
mat ret;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(j==i)
ret.m[i][j] = 1;
else
ret.m[i][j] = 0;
}
}
while(x)
{
if(x&1)
ret = ret * a;
a = a * a;
x>>=1;
}
return ret;
}
ll k_pow(ll a, ll b)
{
ll ret = 1;
while(b)
{
if(b&1)
ret = mod(ret * a);
a = mod(a * a);
b>>=1;
}
return ret;
}
int main()
{
n = 2;
while(~scanf("%lld", &u))
{
u%=240;//第四个循环节，不加就超时
if(u==0)
cout<<0<<endl;
else if(u==1)
cout<<1<<endl;
else
{
init_mat();
q.m[0][0] = 1;
q.m[1][0] = 0;
init.m[0][0] = 3;
init.m[0][1] = 1;
init.m[1][0] = 1;
mat a;
for(int i=0; i<3; i++)
{
MOD = k[i];
a = mat_pow(init, u-1);
a = a*q;
u = a.m[0][0];
}
printf("%lld\n", mod(u));
}
}
return 0;
}