[BZOJ1814]Formula 1

Description:

一个 m * n 的棋盘,有的格子存在障碍,求经过所有非障碍格子的哈密顿回路个数

Hint:

\(n,m<=12\)

Solution:

插头dp模板题,注意要讨论多种情况,详见代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mxn=15,c[4]={0,-1,1,0};
struct data {
    int key; ll val;
};
int n,m,t,ex,ey;
char mp[mxn][mxn];
unordered_map<int ,data > dp[3];
typedef unordered_map<int ,data >::iterator uit;

inline void copy(data x,int id) {dp[id][x.key<<2]=(data){x.key<<2,x.val};} //复制一遍

inline int get(int st,int x) {x<<=1; return (st>>x)&3;}
inline int md(int st,int x,int val) {x<<=1; return (st&(~(3<<x)))|(val<<x);}

inline int getl(int st,int x) {
    int l=x,cnt=1;
    while(cnt!=0) cnt+=c[get(st,--l)];
    return l;
}

inline int getr(int st,int x) {
    int r=x,cnt=-1;
    while(cnt!=0) cnt+=c[get(st,++r)];
    return r;
}

inline void update(int x,int y,data d) 
{
    int st=d.key; ll val=d.val;
    int p=get(st,y),q=get(st,y+1);
    if(mp[x][y]=='*') {
        if(p==0&&q==0) dp[t^1][st]=(data){st,dp[t^1][st].val+val}; 
        return ;
    }
    if(p==0&&q==0) {
        if(x==n-1||y==m-1) return ;
        int nst=md(st,y,1); nst=md(nst,y+1,2);
        dp[t^1][nst]=(data){nst,dp[t^1][nst].val+val};
        return ; //不要少写return
    }
    if(p==0||q==0) {
        if(y<m-1) {
            int nst=md(st,y,0); nst=md(nst,y+1,p+q);
            dp[t^1][nst]=(data){nst,dp[t^1][nst].val+val};
        }
        if(x<n-1) {
            int nst=md(st,y,p+q); nst=md(nst,y+1,0);
            dp[t^1][nst]=(data){nst,dp[t^1][nst].val+val};
        }
        return ;
    }
    int nst=md(st,y,0); nst=md(nst,y+1,0);
    if(p==1&&q==1) nst=md(nst,getr(st,y+1),1);
    if(p==2&&q==2) nst=md(nst,getl(st,y),2);
    if(p==1&&q==2&&(x!=ex||y!=ey)) return ;
    dp[t^1][nst]=(data){nst,dp[t^1][nst].val+val}; 
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;++i) scanf("%s",mp[i]);
    for(int i=0;i<n;++i) 
        for(int j=0;j<m;++j) 
            if(mp[i][j]=='.') ex=i,ey=j;
    t=0; dp[t][0]=(data){0,1ll}; 
    for(int i=0;i<n;++i) {
        dp[2].clear();
        for(uit j=dp[t].begin();j!=dp[t].end();++j) copy((*j).second,2);
        dp[t].clear();
        for(uit j=dp[2].begin();j!=dp[2].end();++j) dp[t][(*j).second.key]=(*j).second; //这里由于map不支持直接修改键值,所以先全部拿出来,再处理
        for(int j=0;j<m;++j) {
            dp[t^1].clear();
            for(uit k=dp[t].begin();k!=dp[t].end();++k) 
                update(i,j,(*k).second);
            t^=1;
        }
    }
    printf("%lld",dp[t][0].val);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/list1/p/10422661.html
1
(1)
>&1