2018ACM_ICPC焦作網路賽L題 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;
}