第二道动规题目,
这道题目卡了我很长时间的,就是因为字典序的问题我一直没想明白。
思路倒是不难,只要题目读懂了,这道题就能很容易的写出来代码。
代码如下:
#include <cstdio> #define M 15 #define N 105 #define INF 0x7fffffff int a[M][N], dp[M][N], pa[M][N]; int m, n; void fun() { for(int i = 0; i < m; i++) dp[i][n-1] = a[i][n-1]; for(int y = n-2; y >= 0; y--) { for(int x = 0; x < m; x++) { int min = INF, minx = x; if(x>0&&x<m-1) { if(min>dp[(x-1+m)%m][y+1]){ min = dp[(x-1+m)%m][y+1]; minx = (x-1+m)%m; } if(min>dp[x][y+1]) { min = dp[x][y+1]; minx = x; } if(min>dp[(x+1)%m][y+1]) { min = dp[(x+1)%m][y+1]; minx = (x+1)%m; } } else if(x==0) { if(min>dp[x][y+1]) { min = dp[x][y+1]; minx = x; } if(min>dp[(x+1)%m][y+1]) { min = dp[(x+1)%m][y+1]; minx = (x+1)%m; } if(min>dp[(x-1+m)%m][y+1]){ min = dp[(x-1+m)%m][y+1]; minx = (x-1+m)%m; } } else { if(min>dp[(x+1)%m][y+1]) { min = dp[(x+1)%m][y+1]; minx = (x+1)%m; } if(min>dp[(x-1+m)%m][y+1]){ min = dp[(x-1+m)%m][y+1]; minx = (x-1+m)%m; } if(min>dp[x][y+1]) { min = dp[x][y+1]; minx = x; } } dp[x][y] = min+a[x][y]; pa[x][y] = minx; } } } int main () { while(~scanf("%d %d",&m,&n)) { for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) scanf("%d",&a[i][j]); fun(); int min = INF, minx; for(int i = 0; i < m; i++) { if(min>dp[i][0]){min = dp[i][0]; minx = i;} } for(int i = 0; i < n; i++) { if(i) printf(" "); printf("%d",minx+1); minx = pa[minx][i]; } printf("\n%d\n",min); } return 0; }