It took nearly 2 hours for the final AC to be cool. A similar to the optimal matrix chain multiplication of the topic, by the "cut the stick" that question of inspiration, the principle of the problem is the same, but become and area, then the corresponding also to increase the dimension.
It is obvious to have a complete representation of the state, with a minimum of four-dimensional arrays, representing the coordinates of its two diagonal vertices, respectively. Then cross-cut or lengthwise, and recursive to find a smaller rectangle, until only one cherry left in the rectangle returns 0
So the question is how to quickly determine how many cherries there are in a rectangle, and then decide to open an array to record the number of cherries in the rectangle. It started out in this place (with a five-cycle), and then came up with a compromise that would distract the complexity of the time. By the efficient chapter, we can first use a two-dimensional array to find out the number of cherries in each interval of each row, thus greatly reducing the complexity of time.
Originally thought this will soon, the result seems also unpleasant, other people in the recursive time to ask the number of cherries unexpectedly also passed. Maybe it's because using memory search recursion will cut off a lot of unnecessary calculations.
See the code for details:
#include <bits/stdc++.h>using namespace Std;const int INF = 1000000;int N,M,K,MAXN = 0,d[22][22][22][22],cnt[22][ 22][22][22],f[22][22];struct point{int x, y;} C[405];int dp (int ux,int uy,int dx,int dy) {int& ans = d[ux][uy][dx][dy]; if (cnt[ux][uy][dx][dy] = = 1) return 0;//recursive boundary if (ans >= 0) return ans; ans = INF; if (uy! = dy) for (int i=uy;i<=dy;i++) {//Slitting if (cnt[ux][uy][dx][i]>0 && cnt[ux][i][dx][dy]>0) ans = min (ans,dp (ux,uy,dx,i) +DP (ux,i+1,dx,dy) + Dx-ux + 1); } if (UX! = dx) for (int i=ux;i<=dx;i++) {//crosscutting if (cnt[ux][uy][i][dy]>0 && cnt[i][uy][dx][dy]>0) ans = min (ANS,DP (i+1,uy,dx,dy) + DP (UX,UY,I,DY) + Dy-uy + 1); } return ans; void Init () {for (int. i=1;i<=k;i++) {for (int. r=1;r<=n;r++) {for (int j=1;j<=m;j++) {///// The number of rows of cherries if (c[i].x = = R && c[i].y <= j) f[r][j]++; }}} for (int ux=1;ux<=n;ux++{for (int. uy=1;uy<=m;uy++) {for (int dx=ux;dx<=n;dx++) {for (int dy=uy;dy<=m;d y++) {int v = 0; for (int i=ux;i<=dx;i++) {v + = F[i][dy]-f[i][uy-1];//Find out part of the answer, separate time complexity} Cnt[ux][uy][dx][dy] = v; }}}}}int main () {while (~scanf ("%d%d%d", &n,&m,&k)) {memset (f,0,sizeof (f)); Memset (d,-1,sizeof (d)); memset (cnt,0,sizeof (CNT)); for (int i=1;i<=k;i++) scanf ("%d%d", &c[i].x,&c[i].y); Init (); printf ("Case%d:%d\n", ++MAXN,DP (1,1,n,m)); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
1629-cake Slicing (DP)