POJ 2353 DP
双向DP+记录路径。
// by SiriusRen
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
stack<int>s;
int n,m,RECL,RECR,minn=0x3fffffff,a[555][555],f[555][555],recl[555][555],recr[555][555];
int main(){
memset(f,0x3f,sizeof(f));
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)scanf("%d",&a[i][j]);
for(int i=1;i<=m;i++)f[1][i]=a[1][i];
for(int i=1;i<=n;i++){
for(int j=1;j<m;j++)if(f[i][j]+a[i][j+1]<f[i][j+1])f[i][j+1]=f[i][j]+a[i][j+1],recl[i][j+1]=j,recr[i][j+1]=i;
for(int j=m;j>1;j--)if(f[i][j]+a[i][j-1]<f[i][j-1])f[i][j-1]=f[i][j]+a[i][j-1],recl[i][j-1]=j,recr[i][j-1]=i;
for(int j=1;j<=m;j++)f[i+1][j]=f[i][j]+a[i+1][j],recl[i+1][j]=j,recr[i+1][j]=i;
}
for(int i=1;i<=m;i++)if(minn>f[n][i])minn=f[n][i],RECL=i;
RECR=n;
while(RECR){
s.push(RECL);
int temp=recr[RECR][RECL];
RECL=recl[RECR][RECL];
RECR=temp;
}
while(!s.empty())printf("%d\n",s.top()),s.pop();
}