【UVA1629】Cake slicing

问题描述

有一个n行m列(1<=n,m<=20)的网络蛋糕上有一些樱桃。每一次可以用一刀沿着网格线把蛋糕切成两块,并且只能够直切不能转弯。要求最后每一块蛋糕上恰好有一个樱桃,且切割线总长度最小。

Input
The input file contains multiple test cases. For each test case: The first line contains three integers, n, m and k (1 ≤ n,m ≤ 20), where n×m is the size of the grid on the cake, and k is the number of the cherries. Then k lines follow. Each line has two integers indicating the position of the unit square with a cherry on it. The two integers show respectively the row number and the column number of the unit square in the grid. All integers in each line should be separated by blanks.
Output
Output an integer indicating the least total length of the cutting edges.
Sample Input
3 4 3 1 2 2 3 3 2
Sample Output
Case 1: 5

题解

挺好的一道记忆化搜索。

用正方形的左右端点表示一个正方形,然后枚举横切和纵切,如果一个方形中没有樱桃,就返回INF,如果有一个就返回0,因为不用再切了嘛。注意枚举的是切得位置所以横纵都加1。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define inf 100000000
using namespace std;
const int maxn=50;
int dp[maxn][maxn][maxn][maxn];
struct node{
 int x,y;
}a[maxn];
int n,m,k;
int dfs(int x1,int y1,int x2,int y2){
 int cnt=0;
 int &tmp=dp[x1][y1][x2][y2];
 if(tmp!=inf) return tmp;
 
 for(int i=1;i<=k;i++)
 if(a[i].x>=x1&&a[i].x<=x2-1&&a[i].y>=y1&&a[i].y<=y2-1)
 cnt++;
 
 if(cnt==1) return 0;
 else if(cnt==0) return inf;
 
 for(int i=x1+1;i<=x2-1;i++){
     tmp=min(tmp,dfs(x1,y1,i,y2)+dfs(i,y1,x2,y2)+(y2-y1));
    }
 for(int j=y1+1;j<=y2-1;j++)
 tmp=min(tmp,dfs(x1,y1,x2,j)+dfs(x1,j,x2,y2)+(x2-x1));
 
 return tmp;
}
int main(){
 int cnt=0;
 while(scanf("%d%d%d",&n,&m,&k)==3){
  for(int i=1;i<=k;i++)
  scanf("%d%d",&a[i].x,&a[i].y);
  
  for(int i=1;i<=n+1;i++)
  for(int j=1;j<=m+1;j++)
  for(int k=1;k<=n+1;k++)
  for(int p=1;p<=m+1;p++)
  dp[i][j][k][p]=inf;
     printf("Case %d: ",++cnt);
     printf("%d\n",dfs(1,1,n+1,m+1));
 }
 return 0;
}
/*
3 4 3
1 2
2 3
3 2
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值