uva 116

单递推的话很简单们,可以正推和逆推,为了求出字典序最小,所以逆推比较好算,用ne存第i第j列 接下来走的是几行,找到起点就可以输出路径了。

代码

#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#include<bits/stdc++.h>
#define int long long
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
 
const int INF = 0x3f3f3f3f;
const double eps = 1e-4;
const int mod = 1e9+7;
const int N = 110;

int n,m;
int a[N][N],dp[N][N];
int ne[N][N],fi,ans = INF;

void print(){
	cout<<fi;
	for(int i=ne[fi][1],j=2;j<=m;i=ne[i][j],j++)
		cout<<" "<<i;
	cout<<"\n"<<ans<<endl;
}

void slove(){
	for(int c=m;c>=1;c--)
		for(int r=1;r<=n;r++){
			if(c == m) dp[r][c] = a[r][c];
			else
			{
				int row[] = {r-1,r,r+1};
				if(r == 1) row[0] = n;
				if(r == n) row[2] = 1;
				sort(row,row+3);
				dp[r][c] = INF;
				for(int k=0;k<3;k++){
					int v = dp[row[k]][c+1] + a[r][c];
					if(v < dp[r][c]){
						dp[r][c] = v;
						ne[r][c] = row[k];//ne存的是当前这个点应该下列往哪行走 
					}
				}
			}
			if(c == 1 && dp[r][c] < ans){
				ans = dp[r][c];
				fi = r;//存第一行最大的那个值 
			}
		}
}

signed main(){
//	IOS;
	#ifdef ddgo
		freopen("C:/Users/asus/Desktop/ddgoin.txt","r",stdin);
	#endif
	
	while(cin>>n>>m){
		ans = INF;
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++)
				cin>>a[i][j];
		slove();
		print();
	}
	
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值