poj 1191

这道题目心得,学会怎么求一个矩阵从(x1,y1)到(x2,y2)的数字的总和,并且还有结合动态规划,
#include"stdafx.h"
#include
<stdio.h>
#include
<math.h>
#include
<algorithm>

using namespace std;

int matrix[8][8];
int s[8][8][8][8];
int dp[15][8][8][8][8];
int cnt;
double sum;

double mmin(double a, double b)
{
return a < b ? a : b;
}

int main()
{
int x1, x2, y1, y2, k, a;
double average, sum = 0;
scanf(
"%d", &cnt);
for (x1=0; x1<8; x1++)
{
for (y1=0; y1<8; y1++)
{
scanf(
"%d", &matrix[x1][y1]);
sum
+= matrix[x1][y1];
}
}

average
= sum/cnt;

for (x1=0; x1<8; x1++)
{
for (y1=0; y1<8; y1++)
{
for (x2=x1; x2<8; x2++)
{
sum
= 0;
for (y2=y1; y2<8; y2++)
{
sum
+= matrix[x2][y2];
if (x2 == x1)
{
s[x1][y1][x2][y2]
= sum;
}
else
{
s[x1][y1][x2][y2]
= s[x1][y1][x2-1][y2] + sum;
}

dp[
0][x1][y1][x2][y2] = s[x1][y1][x2][y2] * s[x1][y1][x2][y2];
}
}
}
}

int temp;

for (k=1; k<=cnt-1; k++)
{
for (x1=0; x1<8; x1++)
{
for (y1=0; y1<8; y1++)
{
for (x2=x1; x2<8; x2++)
{
for (y2=y1; y2<8; y2++)
{
dp[k][x1][y1][x2][y2]
= 2000000000;
for (a=x1; a<x2; a++)
{
temp
= mmin(dp[k-1][x1][y1][a][y2] + s[a+1][y1][x2][y2] * s[a+1][y1][x2][y2],
dp[k
-1][a+1][y1][x2][y2] + s[x1][y1][a][y2] * s[x1][y1][a][y2]);
dp[k][x1][y1][x2][y2]
= mmin(dp[k][x1][y1][x2][y2], temp);
}

for (a=y1; a<y2; a++)
{
temp
= mmin(dp[k-1][x1][y1][x2][a] + s[x1][a+1][x2][y2] * s[x1][a+1][x2][y2],
dp[k
-1][x1][a+1][x2][y2] + s[x1][y1][x2][a] * s[x1][y1][x2][a]);
dp[k][x1][y1][x2][y2]
= mmin(dp[k][x1][y1][x2][y2], temp);
}
}
}
}
}
}

double ret = sqrt((double)dp[cnt-1][0][0][7][7] / (double)cnt - average * average);
printf(
"%.3f\n", ret);

system(
"pause");
return 0;
}
posted @ 2011-05-21 10:26  张兰云  阅读(216)  评论(0编辑  收藏  举报