首页 > 代码库 > UVA 1629 Cake slicing

UVA 1629 Cake slicing

题解:

记忆化搜索

如何判断每个区域只有一个点?转化为区间和,只要区间和为1即可

代码:

#include<bits/stdc++.h>using namespace std;#define pb push_back#define mp make_pair#define se second#define fs first#define LL long long#define CLR(x) memset(x,0,sizeof x)#define MC(x,y) memcpy(x,y,sizeof(x))  #define SZ(x) ((int)(x).size())#define FOR(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1 typedef pair<int,int> P;const double eps=1e-9;const int maxn=200100;const int mod=1e9+7;const int INF=1e9;int n,m,k,a,b;int M[25][25],Sum[25][25];int dp[25][25][25][25];int getsum(int x1,int y1,int x2,int y2){    return Sum[x2][y2]-Sum[x2][y1-1]-Sum[x1-1][y2]+Sum[x1-1][y1-1];}int DP(int x1,int y1,int x2,int y2){    if(dp[x1][y1][x2][y2]>=0)  return dp[x1][y1][x2][y2];    if(getsum(x1,y1,x2,y2)==1) return dp[x1][y1][x2][y2]=0;    int Min=INF;    for(int i=x1;i<x2;i++)    {        if(getsum(x1,y1,i,y2)>0&&getsum(i+1,y1,x2,y2)>0) Min=min(Min,DP(x1,y1,i,y2)+DP(i+1,y1,x2,y2)+y2-y1+1);    }    for(int i=y1;i<y2;i++)    {        if(getsum(x1,y1,x2,i)>0&&getsum(x1,i+1,x2,y2)>0) Min=min(Min,DP(x1,y1,x2,i)+DP(x1,i+1,x2,y2)+x2-x1+1);    }    return dp[x1][y1][x2][y2]=Min;}int main(){    int Case=1;    while(~scanf("%d%d%d",&n,&m,&k))    {        CLR(M);CLR(Sum);        memset(dp,-1,sizeof(dp));        for(int i=1;i<=k;i++)        {            scanf("%d%d",&a,&b);            M[a][b]=1;        }        for(int i=1;i<=n;i++)        for(int j=1;j<=m;j++)        {            Sum[i][j]=M[i][j];            Sum[i][j]+=Sum[i][j-1];            Sum[i][j]+=Sum[i-1][j];            Sum[i][j]-=Sum[i-1][j-1];        }        printf("Case %d: %d\n",Case++,DP(1,1,n,m));    }    return 0;}

 

UVA 1629 Cake slicing