有一个n行m列的网格蛋糕上有一些樱桃,要求延网格线切割,并且每块蛋糕上有一个樱桃,问最小的切割长度。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
int dp[21][21][21][21];
int has[21][21], n, m, k, kase = 0;
int sum(int u, int d, int l, int r) { //有几个樱桃
int cnt = 0;
for(int i = u+1; i <= d; ++i) {
for(int j = l+1; j <= r; ++j) {
if(has[i][j]) cnt++;
if(cnt == 2) return 2;
}
}
return cnt;
}
int dfs(int u, int d, int l, int r) {//up, down, left, right
int &cnt = dp[u][d][l][r]; //dp表示高u到d,宽l到2的最小切割长度
if(cnt != -1) return cnt;
int Count = sum(u,d,l,r);
if(Count == 1) return cnt = 0; //恰好有一个樱桃就不需要在切割了
if(Count == 0) return cnt = INF; //没有樱桃说明这次切割不成立
cnt = INF;
//平行切割
for(int i = u+1; i < d; ++i) cnt = min(cnt, dfs(i, d, l, r) + dfs(u, i, l, r) + r-l);
//垂直切割
for(int i = l+1; i < r; ++i) cnt = min(cnt, dfs(u, d, l, i) + dfs(u, d, i, r) + d-u);
return cnt;
}
int main() {
while(~scanf("%d%d%d", &n, &m, &k)) {
memset(dp, -1, sizeof(dp));
memset(has, 0, sizeof(has));
while(k--) {
int t1, t2; scanf("%d%d", &t1, &t2);
has[t1][t2] = 1;
}
int ans = dfs(0, n, 0, m);
printf("Case %d: %d\n", ++kase, ans);
}
}