目录
传送门:Poor God Water
God Water likes to eat meat, fish and chocolate very much, but unfortunately, the doctor tells him that some sequence of eating will make them poisonous.
Every hour, God Water will eat one kind of food among meat, fish and chocolate. If there are 3 continuous hours when he eats only one kind of food, he will be unhappy. Besides, if there are 3 continuous hours when he eats all kinds of those, with chocolate at the middle hour, it will be dangerous. Moreover, if there are 3 continuous hours when he eats meat or fish at the middle hour, with chocolate at other two hours, it will also be dangerous.
Now, you are the doctor. Can you find out how many different kinds of diet that can make God Water happy and safe during N hours? Two kinds of diet are considered the same if they share the same kind of food at the same hour. The answer may be very large, so you only need to give out the answer module 1000000007.
Input
The fist line puts an integer T that shows the number of test cases.
Each of the next T lines contains an integer NN that shows the number of hours.
Output
For each test case, output a single line containing the answer.
样例输入
3
3
4
15
样例输出
20
46
435170
题意:
有三种食物,如果有3个连续的小时,他只吃一种食物,或者如果他连续3个小时吃各种食物,中间吃巧克力,那将是危险的。此外,如果在中间吃肉或鱼时,连续3个小时,在其他两个小时吃巧克力都是不被允许的,问总共有多少种吃法。
思路:
再枚举每种三小时的吃法的时候,我们发现,只有九种有效吃法,并构成递推,而且有四种吃法是等价的,所以最后可以写出一个五阶矩阵,通过矩阵快速幂求解。
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6 + 7;
const ll mod = 1e9 + 7;
struct Matrix{
ll t[5][5];
};
Matrix Matrix_mul_mod(Matrix a,Matrix b)
{
Matrix temp;
for(int i = 0;i < 5;++i)
for(int j = 0;j < 5;++j){
temp.t[i][j] = 0;
for(int k = 0;k < 5;++k){
temp.t[i][j] += a.t[i][k] * b.t[k][j];
temp.t[i][j] %= mod;
}
}
return temp;
}
Matrix Matrix_fpow_mod(Matrix a,ll b)
{
Matrix res;
for(int i = 0;i < 5;++i)
for(int j = 0;j < 5;++j)
res.t[i][j] = (i == j);
while(b){
if(b & 1) res = Matrix_mul_mod(res,a);
a = Matrix_mul_mod(a,a);
b >>= 1;
}
return res;
}
int main()
{
int t;
ll n;
scanf("%d",&t);
ll k[5]={2,2,2,2,1};
ll res;
while(t--){
Matrix tmp;
res=0;
scanf("%lld",&n);
for(int i = 0;i < 5;++i)
for(int j = 0;j < 5;++j) tmp.t[i][j]= 0;
tmp.t[0][2] = tmp.t[0][3] = tmp.t[1][0] = tmp.t[2][1] = tmp.t[2][2] = tmp.t[2][3] = tmp.t[3][1] = tmp.t[3][2] = tmp.t[4][0] = 1,tmp.t[1][4] = 2;
Matrix ans;
if(n > 2){
ans = Matrix_fpow_mod(tmp,n - 2);
for(int i = 0;i < 5;++i)
for(int j = 0;j < 5;++j)
res=(ans.t[i][j] * k[j] + res) % mod;
}
if(n == 1) res = 3;
if(n == 2) res = 9;
printf("%lld\n",res);
}
return 0;
}