逆向dp,保证字典序最小。
借鉴了小白菜又菜大神的码……
抽空再把书上的敲一遍。嗯……
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
int maps[11][101];
int dp[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 (dp, 0, sizeof (dp) );
for (int i = m ; i >= 1 ; -- i)
for (int j = 1 ; j <= n ; ++ j) {
dp[j][i] = dp[j][i+1]+maps[j][i];
fath[j][i] = j;
if (j > 1 && dp[j][i] >= dp[j-1][i+1]+maps[j][i]) {
dp[j][i] = dp[j-1][i+1]+maps[j][i];
fath[j][i] = j-1;
}
if (j == n && dp[j][i] >= dp[1][i+1]+maps[j][i]) {
dp[j][i] = dp[1][i+1]+maps[j][i];
fath[j][i] = 1;
}
if (j < n && dp[j][i] > dp[j+1][i+1]+maps[j][i]) {
fath[j][i] = j+1;
dp[j][i] = dp[j+1][i+1]+maps[j][i];
}
if (j == 1 && dp[j][i] > dp[n][i+1]+maps[j][i]) {
dp[j][i] = dp[n][i+1]+maps[j][i];
fath[j][i] = n;
}
}
int spa = 1;
for (int i = 2 ; i <= n ; ++ i)
if (dp[spa][1] > dp[i][1]) {
spa = i;
}
int minn = dp[spa][1];
for (int i = 1 ; i <= m ; ++ i) {
if (i < m) { printf ("%d ",spa); }
else { printf ("%d\n%d\n",spa,minn); }
spa = fath[spa][i];
}
}
return 0;
}