题目大意:一块n*m的矩形蛋糕,有k个草莓,现在要将蛋糕切开使每块蛋糕上都恰有一个(这意味着不能切出不含草莓的蛋糕块)草莓,要求只能水平切或竖直切,求最短的刀切长度。
题目分析:定义状态dp(xa,ya,xb,yb)表示矩形左上角为(xa,ya)、右下角为(xb,yb)时需要切的最短长度。那么决策和状态转移方程就很显然了。
代码如下:
# include<iostream> # include<cstdio> # include<cstring> # include<algorithm> using namespace std; const int INF=100000000; int n,m,k,x[500],y[500]; int dp[25][25][25][25]; int DP(int xa,int ya,int xb,int yb) { int &ans=dp[xa][ya][xb][yb]; if(ans!=-1) return ans; int cnt=0; for(int i=0;i<k;++i) if(x[i]>xa&&x[i]<=xb&&y[i]>ya&&y[i]<=yb) ++cnt; if(cnt==1) return ans=0; if(cnt==0) return ans=INF; ans=INF; for(int i=xa+1;i<xb;++i) ans=min(ans,DP(xa,ya,i,yb)+DP(i,ya,xb,yb)+yb-ya); for(int i=ya+1;i<yb;++i) ans=min(ans,DP(xa,ya,xb,i)+DP(xa,i,xb,yb)+xb-xa); return ans; } int main() { int cas=0; while(~scanf("%d%d%d",&n,&m,&k)) { for(int i=0;i<k;++i) scanf("%d%d",&x[i],&y[i]); memset(dp,-1,sizeof(dp)); printf("Case %d: %d ",++cas,DP(0,0,n,m)); } return 0; }