# POJ 1191 棋盘分割 （记忆化搜索）

 Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 14883 Accepted: 5319

Description

Input

Output

Sample Input

3
1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 0
1 1 1 1 1 1 0 3

Sample Output

1.633

### AC 代码

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
using namespace std;
#include<queue>
#include<map>
#define INF (1<<25)

int n,sum[10][10];
int dp[10][10][10][10][16];

int get(int x,int y,int a,int b)
{
return sum[a][b]-sum[a][y-1]-sum[x-1][b]+sum[x-1][y-1];
}

int dfs(int x,int y,int a,int b,int k)
{
if(dp[x][y][a][b][k]!=-1)return dp[x][y][a][b][k];  //记忆化搜索
if(k==1)return (dp[x][y][a][b][k]=get(x,y,a,b)*get(x,y,a,b));   //返回当前块的和的平方
int minn=INF;
for(int i=x; i<a; i++)  //水平切割
{
int l=get(x,y,i,b);
int r=get(i+1,y,a,b);
minn=min(minn,min(dfs(x,y,i,b,k-1)+r*r,dfs(i+1,y,a,b,k-1)+l*l));
}
for(int i=y; i<b; i++)  //垂直切割
{
int l=get(x,y,a,i);
int r=get(x,i+1,a,b);
minn=min(minn,min(dfs(x,y,a,i,k-1)+r*r,dfs(x,i+1,a,b,k-1)+l*l));
}
return (dp[x][y][a][b][k]=minn);
}

int main()
{
while(~scanf("%d",&n))
{
int temp;
memset(sum,0,sizeof(sum));
memset(dp,-1,sizeof(dp));
for(int i=1; i<=8; i++)
for(int j=1; j<=8; j++)
{
scanf("%d",&temp);
sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+temp;   //从(1,1)到(i,j)区域和
}
double avi=sum[8][8]*1.0/n;
printf("%.3f\n",sqrt(dfs(1,1,8,8,n)*1.0/n-avi*avi));
}
return 0;
}