A rectangular cake with a grid of m*n unit squares on its top needs to be sliced into pieces. Several cherries are scattered on the top of the cake with at most one cherry on a unit square. The slicing should follow the rules below:
- each piece is rectangular or square;
- each cutting edge is straight and along a grid line;
- each piece has only one cherry on it.
For example, assume that the cake has a grid of 3 * 4 unit squares on its top, and there are three cherries on the top, as shown in the figure below.
One allowable slicing is as follows.
For this way of slicing, the total length of the cutting edges is 4+2=6.
Another way of slicing is
In this case, the total length of the cutting edges is 3+2=5.
Given the shape of the cake and the scatter of the cherries, you are supposed to find out the least total length of the cutting edges.
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 an integer indicating the least total length of the cutting edges.
3 4 3
1 2
2 3
3 2
Case 1: 5
一道记忆化搜索,实现方法和UVa 10118有相似之处。首先是采用分治思想,将求一块蛋糕的问题划分为求两块蛋糕的问题,切蛋糕花费的代价既状态转移的代价。状态转移方程如下:
enum Sum{ Min{DFS}+CurrentCost }
因为其存在子结构,因此可以利用记忆化搜索进行优化。子结构可对子块的X轴Y轴分别进行枚举,不必离散化。
这道题坑了我整整一下午,有几个原因
- 使用了常数较大的unordered_map
用类似压缩状态的方式表示状态,导致map超时/hash耗费内存过大
#define status x1*1000000+x2*10000+y1*100+y2
在求解某区间内樱桃数目时,采用了枚举樱桃的方法而不是枚举区间
// Created by Chlerry in 2015.
// Copyright (c) 2015 Chlerry. All rights reserved.
//
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define Size 25
#define ll long long
#define mk make_pair
#define pb push_back
#define mem(array, x) memset(array,x,sizeof(array))
typedef pair<int,int> P;
int n,m,k,tx,ty;
int cost[Size][Size][Size][Size];
bool has[Size][Size];
int sum(int x1,int x2,int y1,int y2)
{
int ret=0;
for(int i=x1;i<=x2;i++)
for(int j=y1;j<=y2;j++)
{
if (has[i][j]) ret++;
if (ret==2) return 2;
}
return ret;
}
int DFS(int x1,int x2,int y1,int y2)
{
int &ret=cost[x1][x2][y1][y2];
if(ret!=-1)
return ret;
int cnt=sum(x1,x2,y1,y2);
if(cnt==1) return ret=0;
if(!cnt) return ret=INT_MAX/3;
ret=INT_MAX;
for(int i=x1;i1,x2,y1,y2)+y2-y1+1);
for(int i=y1;i1,y2)+x2-x1+1);
return ret;
}
int main()
{
//freopen("in.txt","r",stdin);
for(int ca=1;cin>>n>>m>>k;ca++)
{
mem(cost,-1);mem(has,0);
for(int i=0;icin>>tx>>ty,has[tx][ty]=1;
cout<<"Case "<": "<1,n,1,m)<return 0;
}