1. 程式人生 > >HDU - 6185 :Covering(矩陣乘法&狀態壓縮)

HDU - 6185 :Covering(矩陣乘法&狀態壓縮)

Bob's school has a big playground, boys and girls always play games here after school.

To protect boys and girls from getting hurt when playing happily on the playground, rich boy Bob decided to cover the playground using his carpets.

Meanwhile, Bob is a mean boy, so he acquired that his carpets can not overlap one cell twice or more.

He has infinite carpets with sizes of
1×2">1×1×2 and 2×2×1 , and the size of the playground is 4×4×n .

Can you tell Bob the total number of schemes where the carpets can cover the playground completely without overlapping?

InputThere are no more than 5000 test cases.

Each test case only contains one positive integer n in a line.

1≤n≤1018">1n10 18  1≤n≤1018
OutputFor each test cases, output the answer mod 1000000007 in a line.
Sample Input

1
2

Sample Output

1
5

題意:給定4*N的矩陣,用1*2或者2*1的地毯去覆蓋,問多少種方案。

思路:開始想的狀態壓縮求出矩陣,但是矩陣是16*16的,T了。然後發現,16割狀態裡有用的(最後可以到達15這個狀態)只有5個:0,3,6,9,15。 所以矩陣的大小為5。就可以過了。

(至於他們的公式:f(n)=f(n-1)+5*f(n-2)+f(n-3)-f(n-4)。在下是不會推的。

(狀態壓縮可以參考此題:https://www.cnblogs.com/hua-dong/p/7967023.html

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
using namespace std;
const int Mod=1e9+7;struct mat
{
    ll mp[6][6];
    mat(){memset(mp,0,sizeof(mp)); }
    mat friend operator *(mat a,mat b)
    {
        mat res;
        rep(k,0,5)
         rep(i,0,5)
          rep(j,0,5)
            res.mp[i][j]=(res.mp[i][j]+(a.mp[i][k]*b.mp[k][j]%Mod))%Mod;
        return res;
    }
    mat friend operator ^(mat a,ll x)
    {
        mat res;
        rep(i,0,5) res.mp[i][i]=1;
        while(x){
            if(x&1) res=res*a;  a=a*a;  x>>=1;
        }   return res;
    }
};
int main()
{
    ll N; mat base;
    base.mp[0][5]=base.mp[1][3]=base.mp[1][5]=1;
    base.mp[2][5]=base.mp[3][1]=base.mp[3][5]=1;
    base.mp[5][0]=base.mp[5][1]=base.mp[5][2]=1;
    base.mp[5][3]=base.mp[5][5]=base.mp[2][4]=base.mp[4][2]=1;
    while(~scanf("%lld",&N)){
        mat ans; ans.mp[0][5]=1;
        ans=ans*(base^N);
        printf("%d\n",ans.mp[0][5]);
    }
    return 0;
}