题目:一个二维的矩阵,从左向右找到一条路径,每次可以移动到右侧,右上或者右下的格子中,
要求找到一条,路径上的数字和最小的路径,输出路径(和相同时输出字典序最小的)。
分析:dp,动态三角形。因为要字典序最小逆序求解,记录输出即可,最优解取决于相邻的三个元素。
说明:注意输出格式。
#include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> using namespace std; int maps[11][101]; int smap[11][101]; int fath[11][101]; int main() { int n,m; while (~scanf("%d%d",&n,&m)) { for (int i = 1 ; i <= n ; ++ i) for (int j = 1 ; j <= m ; ++ j) scanf("%d",&maps[i][j]); memset(smap, 0, sizeof(smap)); for (int i = m ; i >= 1 ; -- i) for (int j = 1 ; j <= n ; ++ j) { smap[j][i] = smap[j][i+1]+maps[j][i]; fath[j][i] = j; if (j > 1 && smap[j][i] >= smap[j-1][i+1]+maps[j][i]) { smap[j][i] = smap[j-1][i+1]+maps[j][i]; fath[j][i] = j-1; } if (j == n && smap[j][i] >= smap[1][i+1]+maps[j][i]) { smap[j][i] = smap[1][i+1]+maps[j][i]; fath[j][i] = 1; } if (j < n && smap[j][i] > smap[j+1][i+1]+maps[j][i]) { smap[j][i] = smap[j+1][i+1]+maps[j][i]; fath[j][i] = j+1; } if (j == 1 && smap[j][i] > smap[n][i+1]+maps[j][i]) { smap[j][i] = smap[n][i+1]+maps[j][i]; fath[j][i] = n; } } int spa = 1; for (int i = 2 ; i <= n ; ++ i) if (smap[spa][1] > smap[i][1]) spa = i; int min = smap[spa][1]; for (int i = 1 ; i <= m ; ++ i) { if (i < m) printf("%d ",spa); else printf("%d\n%d\n",spa,min); spa = fath[spa][i]; } } return 0; }
原文:http://blog.csdn.net/mobius_strip/article/details/42877143