Description
将一个8*8的棋盘进行如下分割:将原棋盘割下一块矩形棋盘并使剩下部分也是矩形,再将剩下的部分继续如此分割,这样割了(n-1)次后,连同最后剩下的矩形棋盘共有n块矩形棋盘。(每次切割都只能沿着棋盘格子的边进行)
原棋盘上每一格有一个分值,一块矩形棋盘的总分为其所含各格分值之和。现在需要把棋盘按上述规则分割成n块矩形棋盘,并使各矩形棋盘总分的均方差最小。
均方差 ,其中平均值 ,x i为第i块矩形棋盘的总分。
请编程对给出的棋盘及n,求出O'的最小值。
原棋盘上每一格有一个分值,一块矩形棋盘的总分为其所含各格分值之和。现在需要把棋盘按上述规则分割成n块矩形棋盘,并使各矩形棋盘总分的均方差最小。
均方差 ,其中平均值 ,x i为第i块矩形棋盘的总分。
请编程对给出的棋盘及n,求出O'的最小值。
Input
第1行为一个整数n(1 < n < 15)。
第2行至第9行每行为8个小于100的非负整数,表示棋盘上相应格子的分值。每行相邻两数之间用一个空格分隔。
第2行至第9行每行为8个小于100的非负整数,表示棋盘上相应格子的分值。每行相邻两数之间用一个空格分隔。
Output
仅一个数,为O'(四舍五入精确到小数点后三位)。
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
/*
每次切割都分4种情况,按竖切然后在左继续切,按横切然后在右继续切,或者
按横切然后在上继续切或者按横切然后在下继续切。
本来我是直接裸着递归,TLE。。
递推~~~
*/
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int sum[10][10][10][10];
int dp[20][10][10][10][10];
int key[10][10];
#define inf 0x3f3f3f3f
inline int min(int a,int b)
{
return a>b?b:a;
}
void init()
{
for(int r1=1;r1<=8;r1++)
{
for(int c1=1;c1<=8;c1++)
{
for(int r2=1;r2<=8;r2++)
{
for(int c2=1;c2<=8;c2++)
{
int temp=0;
for(int i=r1;i<=r2;i++)
{
temp+=key[i][c2];
}
if(c1==1&&r1==1)sum[r1][c1][r2][c2]=sum[r1][c1][r2][c2-1]+temp;
else sum[r1][c1][r2][c2]=sum[1][1][r2][c2]-sum[1][1][r1-1][c2]-sum[1][1][r2][c1-1]+sum[1][1][r1-1][c1-1];
dp[0][r1][c1][r2][c2]=sum[r1][c1][r2][c2]*sum[r1][c1][r2][c2];
}
}
}
}
}
int main()
{
int k;
while(scanf("%d",&k)!=EOF)
{
for(int i=1;i<=8;i++)
{
for(int j=1;j<=8;j++)
{
scanf("%d",&key[i][j]);
}
}
init();
for(int p=1;p<k;p++)
{
for(int r1=1;r1<=8;r1++)
{
for(int c1=1;c1<=8;c1++)
{
for(int r2=1;r2<=8;r2++)
{
for(int c2=1;c2<=8;c2++)
{
int temp=inf;
for(int a=r1;a<r2;a++)
{
int temp1=min(dp[p-1][r1][c1][a][c2]+dp[0][a+1][c1][r2][c2],dp[p-1][a+1][c1][r2][c2]+dp[0][r1][c1][a][c2]);
temp=min(temp,temp1);
}
for(int b=c1;b<c2;b++)
{
int temp1=min(dp[p-1][r1][c1][r2][b]+dp[0][r1][b+1][r2][c2],dp[p-1][r1][b+1][r2][c2]+dp[0][r1][c1][r2][b]);
temp=min(temp,temp1);
}
dp[p][r1][c1][r2][c2]=temp;
}
}
}
}
}
double x_=(double)(sum[1][1][8][8])/k;//说明sum并没有求错
x_*=x_;
double ans=((double)(dp[k-1][1][1][8][8])/k)-x_;
ans=sqrt(ans);
printf("%.3lf\n",ans);
}
return 0;
}