题意:有8*8的棋盘每个格子有不超过100的数字(答案不会超int),现在想把棋盘分成n份,满足每个分割线要沿着边界,问最后使得均方差最小。
题解:把原式化简,即为sqrt (dp[1][1][8][8][n] * 1.0 / n - ave * ave ),想到dp[x1][x2][y1][y2][num]表示把整个棋盘分成num份得到的最小平方和是多少,
很容易想到记忆化dfs,枚举当前横竖切割的位置,然后就没有然后了。
Sure原创,转载请注明出处。
#include <iostream> #include <cstdio> #include <memory.h> #include <cmath> #define MIN(a , b) ((a) < (b) ? (a) : (b)) using namespace std; const int inf = 1 << 29; const int maxn = 16; int map[10][10],sum[10][10],dp[10][10][10][10][maxn]; bool vis[10][10][10][10][maxn]; int n; void read() { memset(sum,0,sizeof(sum)); memset(vis,false,sizeof(vis)); for(int i=1;i<=8;i++) { for(int j=1;j<=8;j++) { scanf("%d",&map[i][j]); } } for(int i=1;i<=8;i++) { for(int j=1;j<=8;j++) { sum[i][j] = sum[i-1][j] + sum[i][j-1]- sum[i-1][j-1] + map[i][j]; } } return; } int dfs(int x1,int x2,int y1,int y2,int num) { if(num == 1) { vis[x1][x2][y1][y2][num] = true; int tmp = sum[x2][y2] - sum[x2][y1-1] - sum[x1-1][y2] + sum[x1-1][y1-1]; return dp[x1][x2][y1][y2][num] = tmp * tmp; } if(vis[x1][x2][y1][y2][num]) { return dp[x1][x2][y1][y2][num]; } int res = inf; for(int i=x1;i<x2;i++) { res = MIN(res , dfs(x1,i,y1,y2,num-1) + dfs(i+1,x2,y1,y2,1)); res = MIN(res , dfs(x1,i,y1,y2,1) + dfs(i+1,x2,y1,y2,num-1)); } for(int i=y1;i<y2;i++) { res = MIN(res , dfs(x1,x2,y1,i,num-1) + dfs(x1,x2,i+1,y2,1)); res = MIN(res , dfs(x1,x2,y1,i,1) + dfs(x1,x2,i+1,y2,num-1)); } vis[x1][x2][y1][y2][num] = true; return dp[x1][x2][y1][y2][num] = res; } void solve() { int tot = dfs(1,8,1,8,n); double ave = sum[8][8] / (n * 1.0); double ans = tot * 1.0 / n - ave * ave; printf("%.3f\n",sqrt(ans)); return; } int main() { while(~scanf("%d",&n)) { read(); solve(); } return 0; }