8 2 3 13 2 6 6 3 5 7 4 4 14 5 2 21 5 6 4 6 3 15 7 2 14 0 0 0
67
// 二取方格数 多进程dp
我们令 dp[x1,y1,x2,y2]表示第一条路径走到了(x1,y1),第二条路径走到了(x2,y2)是的最优解,可以很自然的得到状态转移方程:
设p=max(sum[i1-1,j1,i2-1,j2],sum[i1-1,j1,i2,j2-1],sum[i1,j1-1,i2-1,j2],sum[i1,j1-1,i2,j2-1])
dp[x1][y1][x2][y2]= 0 (x1||y1||x2||y2==0)
= p+data[x1][y1] (x1==x2&&y1==y2)
= p+data[x1][y1]+data[x2][y2] (x1!=x2||y1!=y2)
#include<cstdio> #include<cstring> int dp[15][15][15][15],p[15][15]; int main() { int n,i1,j1,i2,j2,x,y,z; while(scanf("%d",&n)!=EOF) { memset(dp,0,sizeof(dp)); memset(p,0,sizeof(p)); while(1) { scanf("%d%d%d",&x,&y,&z); if(x+y+z==0) break; p[x][y]=z; } for(i1=1;i1<=n;i1++) for(j1=1;j1<=n;j1++) for(i2=1;i2<=n;i2++) for(j2=1;j2<=n;j2++) { if(dp[i1-1][j1][i2-1][j2]>dp[i1][j1][i2][j2]) dp[i1][j1][i2][j2]=dp[i1-1][j1][i2-1][j2]; if(dp[i1-1][j1][i2][j2-1]>dp[i1][j1][i2][j2]) dp[i1][j1][i2][j2]=dp[i1-1][j1][i2][j2-1]; if(dp[i1][j1-1][i2-1][j2]>dp[i1][j1][i2][j2]) dp[i1][j1][i2][j2]=dp[i1][j1-1][i2-1][j2]; if(dp[i1][j1-1][i2][j2-1]>dp[i1][j1][i2][j2]) dp[i1][j1][i2][j2]=dp[i1][j1-1][i2][j2-1]; dp[i1][j1][i2][j2]+=p[i1][j1]; if(i1!=i2||j1!=j2) dp[i1][j1][i2][j2]+=p[i2][j2]; } printf("%d\n",dp[n][n][n][n]); } return 0; }
原文地址:http://blog.csdn.net/u012773338/article/details/38061189