标签:blog io os 使用 sp for on 2014 log
题目:在一个二维的平面网格中从左西向右走,每个格子里有个数字每次只能走到本行或者上一行或者下一行;
求一条从西到东的路径,使得路径上的数字和最大,如果都是最大,找到最路径小字典序列。
分析:dp,动态三角形类似物。逆向求解方便找到最小字典序。
状态:f(i,j)为从(i,j)位置开始走到最右侧的最大值;
转移方程:f(i,j)= data(i,j)+ max(f(i+1,j),f(i+1,j-1),f(i+1,j+1));
记录路径后继,用于输出。
说明:使用从后向前计算,得到最小字典序。
#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; }
标签:blog io os 使用 sp for on 2014 log
原文地址:http://blog.csdn.net/mobius_strip/article/details/41907293