原题链接
思路
代码
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
ll x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-')f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9')
{
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b, ll p)
{
ll res = 1;
while(b)
{
if(b & 1)res = res * a % p;
a = a * a % p;
b >>= 1;
}
return res;
}
const int inf = 0x3f3f3f3f;
#define PI acos(-1)
const int maxn =210;
int n,m,mp[maxn][maxn];
int dp[maxn][maxn],path[maxn][maxn];
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
mp[i][j]=read;
memset(dp,0x3f,sizeof dp);
memset(path,0,sizeof path);
for(int j=m;j;j--){
for(int i=1;i<=n;i++){
if(j==m) dp[i][j]=mp[i][j];
else{
int a[3]={i,i+1,i-1};
if(i==1) a[2]=n;
if(i==n) a[1]=1;
sort(a,a+3);
for(int k=0;k<3;k++){
int t=dp[a[k]][j+1]+mp[i][j];
if(t<dp[i][j]){
dp[i][j]=t;
path[i][j]=a[k];
}
}
}
}
}
int res=inf,pos;
for(int i=1; i<=n; i++)
if(dp[i][1]<res){
res=dp[i][1];pos=i;
}
printf("%d",pos);
for(int i=path[pos][1],j=2;j<=m;i=path[i][j],j++)
printf(" %d",i);
puts("");
printf("%d\n",res);
}
return 0;
}