一道裸地dp
有3*(k+1)*m*n种状态
1Y
在心情低落忧伤过度至溢出之时
刷题=.=
dp[i][j][x][y]
i,j表示坐标
x表示方向,0表示从上面下来1,2表示两个方向
y表示当前负数个数
#include <cstdio>
#include<algorithm>
using namespace std;
#define IMP (-(int)1e9)
#define FOR(i,a,b) for(i=a;i<=b;i++)
int dp[80][80][10][10];
int grid[80][80];
int main(){
int n,k;
int z=0;
while(scanf("%d%d",&n,&k)!=EOF){
if(!n&&!k)break;
int i,j,x,y;
FOR(i,1,n)FOR(j,1,n)scanf("%d",&grid[i][j]);
FOR(i,1,n)FOR(j,1,n)FOR(x,0,2)FOR(y,0,k)dp[i][j][x][y]=IMP;
if(grid[1][1]<0)FOR(x,0,2)dp[1][1][x][1]=grid[1][1];
else FOR(x,0,2)dp[1][1][x][0]=grid[1][1];
i=1;
FOR(j,2,n){
int add=0;if(grid[i][j]<0)add=1;
for(y=0;y+add<=k;y++){
if(dp[i][j-1][2][y]!=IMP)dp[i][j][2][y+add]=dp[i][j-1][2][y]+grid[i][j];
}
}
FOR(i,2,n){
FOR(j,1,n){
int add=0;if(grid[i][j]<0)add=1;
for(y=0;y+add<=k;y++){
int temp=IMP;
FOR(x,0,2)if(dp[i-1][j][x][y]!=IMP)temp=max(temp,dp[i-1][j][x][y]);
if(temp!=IMP)FOR(x,0,2)dp[i][j][x][y+add]=temp+grid[i][j];
}
} //初始化dp
FOR(j,2,n){
int add=0;if(grid[i][j]<0)add=1;
for(y=0;y+add<=k;y++){
int temp=dp[i][j-1][2][y];
int &t=dp[i][j][2][y+add];
if(temp!=IMP)t=max(t,temp+grid[i][j]);
}
}
for(j=n-1;j>=1;j--){
int add=0;if(grid[i][j]<0)add=1;
for(y=0;y+add<=k;y++){
int temp=dp[i][j+1][1][y];
int &t=dp[i][j][1][y+add];
if(temp!=IMP)t=max(t,temp+grid[i][j]);
}
}
} //i主循环
int res=IMP;
FOR(y,0,k)FOR(x,0,2)if(dp[n][n][x][y]!=IMP)res=max(res,dp[n][n][x][y]);
/* FOR(y,0,k)FOR(x,0,2){
printf("x=%d,y=%d\n",x,y);
FOR(i,1,n){
FOR(j,1,n)if(dp[i][j][x][y]!=IMP)printf("%4d",dp[i][j][x][y]);
else printf(" IMP");
printf("\n");
}
} */
printf("Case %d: ",++z);
if(res==IMP)printf("impossible\n");
else printf("%d\n",res);
}
return 0;
}