题解:
简单的插头dp
加上一个代价即可
代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=,HASH=,STATE=,M=1e9+;
typedef long long ll;
int n,m,ch[N],code[N],mp[N][N],mp2[N][N];
struct HASHMAP
{
int head[HASH],next[STATE],size;
ll state[STATE],f[STATE];
void init()
{
size=;
memset(head,-,sizeof(head));
}
void push(ll st,ll ans)
{
int h=st%HASH;
for (int i=head[h];i!=-;i=next[i])
if (state[i]==st)
{
f[i]=max(ans,f[i]);
return;
}
state[size]=st;
f[size]=ans;
next[size]=head[h];
head[h]=size++;
}
}hm[];
void decode(ll st)
{
for (int i=m;i>=;i--)
{
code[i]=st&;
st>>=;
}
}
ll encode()
{
int cnt=;
ll st=;
memset(ch,-,sizeof(ch));
ch[]=;ch[]=;
for (int i=;i<=m;i++)
{
if (ch[code[i]]==-)ch[code[i]]=cnt++;
code[i]=ch[code[i]];
st<<=;
st|=code[i];
}
return st;
}
void shift()
{
for (int i=m;i;i--)code[i]=code[i-];
code[]=;
}
void dp(int r,int c,int cur)
{
for (int k=;k<hm[cur].size;k++)
{
decode(hm[cur].state[k]);
int up=code[c],left=code[c-];
if ((r==&&c==)||(r==n&&c==m))
{
if (!up&&!left)
{
if (c<m)
{
code[c]=;
code[c-]=;
hm[cur^].push(encode(),hm[cur].f[k]+mp[r][c]);
}
if (r<n)
{
code[c]=;
code[c-]=;
if (m==c)shift();
hm[cur^].push(encode(),hm[cur].f[k]+mp[r][c]);
}
}
if (up||left)
{
code[c]=code[c-]=;
if (m==c)shift();
hm[cur^].push(encode(),hm[cur].f[k]+mp[r][c]);
}
continue;
}
if (up&&left)
{
if (up!=left)
{
int t=max(up,left);
code[c]=code[c-]=;
for (int i=;i<=m;i++)
if (code[i]==left||code[i]==up)code[i] = t;
if (m==c) shift();
hm[cur^].push(encode(),hm[cur].f[k]+mp[r][c]);
}
}
else if (up||left)
{
if (c<m)
{
code[c-]=;
code[c]=up|left;
if (m==c)shift();
hm[cur^].push(encode(),hm[cur].f[k]+mp[r][c]);
}
if (r<n)
{
code[c-]=up|left;
code[c]=;
if (m==c) shift();
hm[cur^].push(encode(),hm[cur].f[k]+mp[r][c]);
}
}
else
{
if (c<m&&r<n)
{
code[c-]=code[c]=;
hm[cur^].push(encode(),hm[cur].f[k]+mp[r][c]);
}
code[c]=code[c-]=;
if (c==m) shift();
hm[cur^].push(encode(),hm[cur].f[k]);
}
}
}
int main()
{
int cas=;
while (~scanf("%d%d",&n,&m))
{
for (int i=;i<=n;i++)
for (int j=;j<=m;j++)scanf("%d", &mp[i][j]);
if (n==&&m==)
{
printf("Case %d: %d\n",++cas,mp[][]);
continue;
}
if (n<m)
{
for (int i=;i<=m;i++)
for (int j=;j<=n;j++)mp2[i][j]=mp[j][i];
for (int i=;i<=m;i++)
for (int j=;j<=n;j++)mp[i][j]=mp2[i][j];
swap(n,m);
}
int cur=;
hm[cur].init();
hm[cur].push(,);
for (int i=;i<=n;i++)
for (int j=;j<=m;j++)
{
hm[cur^].init();
dp(i,j,cur);
cur^=;
}
ll ans=-1e18;
for (int i=;i<hm[cur].size;i++)ans=max(ans,hm[cur].f[i]);
printf("Case %d: %lld\n",++cas,ans);
}
return ;
}