在一个n*m的棋盘上,每个格子有权值,让你找一条简单回路使得经过的格子权值和最大。n<=100,m<=6
插头dp经典题目。复杂度O(nm3mm)" role="presentation" >
O(nm3mm)
#include
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
#define N 3000
inline char gc(){
static char buf[1<<16],*S,*T;
if(T==S){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
return *S++;
}
inline int read(){
int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=gc();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
return x*f;
}
int n,m,mp[110][7],pp,ans=-inf,c[]={0,-1,1,0};
struct Hash_table{
int next,key,val;
};
struct Icefox{
int h[N],num;
Hash_table data[N];
inline void init(){num=0;memset(h,0,sizeof(h));}
inline void ins(int key,int val){
int x=key%N;
for(int i=h[x];i;i=data[i].next)
if(key==data[i].key){data[i].val=max(data[i].val,val);return;}
data[++num].key=key;data[num].next=h[x];h[x]=num;data[num].val=val;
}
}dp[2];
inline int get1(int S,int x){x<<=1;return S>>x&3;}
inline int set1(int S,int x,int val){x<<=1;return S&~(3<inline int getr(int S,int r){
int cnt=-1;
while(cnt) cnt+=c[get1(S,++r)];return r;
}
inline int getl(int S,int l){
int cnt=1;
while(cnt) cnt+=c[get1(S,--l)];return l;
}
inline void update(int x,int y,int S,int val){
int p=get1(S,y),q=get1(S,y+1),ss;
if(!p&&!q){
ss=set1(S,y,0);ss=set1(ss,y+1,0);
dp[pp^1].ins(ss,val-mp[x][y]);
if(x==n-1||y==m-1) return;
ss=set1(S,y,1);ss=set1(ss,y+1,2);
dp[pp^1].ins(ss,val);return;
}if(!p||!q){
if(x1){
ss=set1(S,y,p+q);ss=set1(ss,y+1,0);
dp[pp^1].ins(ss,val);
}if(y1){
ss=set1(S,y+1,p+q);ss=set1(ss,y,0);
dp[pp^1].ins(ss,val);
}return;
}ss=set1(S,y,0);ss=set1(ss,y+1,0);
if(p==1&&q==1) ss=set1(ss,getr(S,y+1),1);
if(p==2&&q==2) ss=set1(ss,getl(S,y),2);
if(p==1&&q==2){if(!ss) ans=max(ans,val);return;}
dp[pp^1].ins(ss,val);
}
int main(){
n=read();m=read();
for(int i=0;ifor(int j=0;j0;dp[pp].init();dp[pp].ins(0,0);
for(int i=0;ifor(int j=1;j<=dp[pp].num;++j) dp[pp].data[j].key<<=2;
for(int j=0;j1].init();
for(int k=1;k<=dp[pp].num;++k)
update(i,j,dp[pp].data[k].key,dp[pp].data[k].val+mp[i][j]);
pp^=1;
}
}printf("%d\n",ans);
return 0;
}