UVa 1629 Cake slicing (记忆化搜索)

题目链接:https://cn.vjudge.net/problem/UVA-1629

题意:一个n行m列的蛋糕上有一些樱桃,每次可以水平或竖直切一刀,要求最后每块蛋糕上恰有一块樱桃,求最小切割长度。

思路:用dp(r1, r2, c1, c2, k)表示当前矩形区域为[r1,r2],[c1,c2]且该区域有k块蛋糕时的最小切割长度。当k为1时,答案为0;当k>1时,递归的进行横切或者竖切即可。


#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const int maxn = 25;
const int INF = 1e6 + 10;
int food[maxn][maxn];
int d[maxn][maxn][maxn][maxn];
int r, c, k;

int dp(int r1, int r2, int c1, int c2, int k)
{
    if(r2 < r1 || c2 < c1) return 0;
    int &ans = d[r1][r2][c1][c2];
    if(ans >= 0) return ans;
    if(k == 1) return ans = 0;
    ans = INF;
    int sum = 0;
    for(int i = r1; i <= r2; ++i) {
       for(int j = c1; j <= c2; ++j)
          if(food[i][j]) ++sum;
       if(sum > 0 && sum < k) ans = min(ans, dp(r1, i, c1, c2, sum) + dp(i+1, r2, c1, c2, k-sum) + c2-c1+1); //横着切
    }
    sum  = 0;
    for(int j = c1; j <= c2; ++j) {
       for(int i = r1; i <= r2; ++i)
         if(food[i][j]) ++sum;
       if(sum > 0 && sum < k) ans = min(ans, dp(r1, r2, c1, j, sum) + dp(r1, r2, j+1, c2, k-sum) + r2-r1+1); //竖着切
    }
    return ans;
}

int main()
{
   int kase = 0;
   while(scanf("%d%d%d", &r,&c,&k) == 3) {
      memset(food, 0, sizeof food);
      memset(d, -1, sizeof d);
      for(int i = 0; i < k; i++) {
         int x, y;
         scanf("%d%d", &x, &y);
         food[x][y] = 1;
      }
      printf("Case %d: %d\n", ++kase, dp(1, r, 1, c, k));
   }
}


你可能感兴趣的:(动态规划,UVa)