点头OJ 1033 . 骨牌覆盖 V2 ( 状态压缩 + 矩阵快速幂 )

题目链接~~>

做题感悟:先前做过一个类似的题,是俄罗斯的一道区域赛的题目,也是用的状态压缩 + 矩阵快速幂。

解题思路:状态压缩 + 矩阵快速幂

                构造一个矩阵 B [ i ] [ j ] 代表状态 i ,与状态 j 是否合法,j 代表上一行的状态,如果合法为 1 ,否则为 0 ,这样如果再得到初始各种状态的方案数的矩阵 A ,A 只有一列 ,这样 B * A 就是第二行各种状态对应 的方案数 。这样再加上矩阵快速幂就解决了。


代码:

#include<iostream>
#include<sstream>
#include<map>
#include<cmath>
#include<fstream>
#include<queue>
#include<vector>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<stack>
#include<bitset>
#include<ctime>
#include<string>
#include<cctype>
#include<iomanip>
#include<algorithm>
using namespace std  ;
#define INT long long int
#define L(x)  (x * 2)
#define R(x)  (x * 2 + 1)
const int INF = 0x3f3f3f3f ;
const double esp = 0.00000000001 ;
const double PI = acos(-1.0) ;
const INT mod = 1000000007 ;
const int MY = (1<<5) + 5 ;
const int MX = (1<<13) + 5 ;
const int S = 20 ;
int n ,m ;
INT key[50] ;
struct M
{
    INT p[32][32] ;
    M()
    {
        memset(p ,0 ,sizeof(p)) ;
    }
    void init()
    {
        for(int i = 0 ;i < (1<<m) ; ++i)
           p[i][i] = 1 ;
    }
    M operator *(const M& a)
    {
        M c ;
        for(int i = 0 ;i < (1<<m) ; ++i)
          for(int k = 0 ;k < (1<<m) ; ++k)
            if(p[i][k])
              for(int j = 0 ;j < (1<<m) ; ++j)
                 c.p[i][j] = (c.p[i][j] + p[i][k]*a.p[k][j])%mod ;
        return c ;
    }
};
M pow(M a ,int k)  // 矩阵快速幂
{
    M b ;
    b.init() ;
    while(k)
    {
        if(k&1)  b = a * b ;
        a = a * a ;
        k >>= 1 ;
    }
    return b ;
}
void dfs(int S ,int cnt ,int tx ,int S1 ,M& c)
{
    if(cnt == m)
    {
        c.p[S][tx] = 1 ;
        if(S1 == 0)   key[S] = 1 ;
        return ;
    }
    if(cnt + 2 <= m && !(S&(1<<cnt)) && !(S&(1<<(cnt+1))))
         dfs(S|(1<<cnt)|(1<<(cnt+1)) ,cnt+2 ,tx ,S1 ,c) ;
    dfs(S ,cnt+1 ,tx ,S1 ,c) ;
}
int main()
{
    //freopen("input.txt" ,"r" ,stdin) ;
    while(~scanf("%d%d" ,&n ,&m))
    {
        M c ;
        for(int i = 0 ;i < (1<<m) ; ++i)  // 处理各种对应的状态  同时初始化第一行的状态
            dfs((~i)&((1<<m)-1) ,0 ,i ,(~i)&((1<<m)-1) ,c) ;
        M b = pow(c ,n-1) ;
        INT ans = 0 ;
        for(int i = 0 ;i < (1<<m) ; ++i)
             ans = (ans + b.p[(1<<m)-1][i]*key[i])%mod ;
        cout<<ans%mod<<endl ;
    }
    return 0 ;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linux猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值