设为首页 加入收藏

TOP

uva116 - Unidirectional TSP(记忆化搜索)
2015-07-20 17:50:25 来源: 作者: 【 】 浏览:3
Tags:uva116 Unidirectional TSP 记忆 搜索

题目:uva116 - Unidirectional TSP(记忆化搜索)


题目大意:给出一个数组,然后可以从第一列任意一行(i, 0)开始走,只能走三个位置(i + 1, 1) (i, 1), (i - 1, 0) 并且这里默认第一行和最后一行是相连着的,就是当i+ 1或着i - 1超出边界那么就到另一头的边界。最后输出字典序最小的路径。


解题思路:记忆化搜索。dp【x】【y】 =Min( dp【x + dir【i】【0】】【y + dir【i】【0】】 + mat【x】【y】)。


代码:

#include 
  
   
#include 
   
     const int N = 15; const int M = 105; const int INF = 0x3f3f3f3f; const int dir[3][2] = {{0, 1}, {1, 1}, {-1, 1}}; int mat[N][M]; int f[N][M]; int path[N][M]; int n, m; int Min (const int a, const int b) { return a < b ? a: b; } void init () { for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) { f[i][j] = INF; path[i][j] = n; } } int dp (int x, int y) { int& ans = f[x][y]; if (y == m) return ans = 0; if (ans != INF) return ans; int nx, ny; int temp; for (int i = 0; i < 3; i++) { nx = x + dir[i][0]; ny = y + dir[i][1]; if (nx == -1) nx = n - 1; if (nx == n) nx = 0; temp = dp(nx, ny) + mat[x][y]; if (temp <= ans) { if (temp == ans) path[x][y] = Min (path[x][y], nx); else path[x][y] = nx; ans = temp; } } return ans; } void printf_ans (int x, int y) { if (y == m - 1) return; printf (" %d", path[x][y] + 1); printf_ans(path[x][y], y + 1); } int main () { while (scanf ("%d%d", &n, &m) != EOF) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) scanf ("%d", &mat[i][j]); init(); int ans = INF; int temp, r; for (int i = n - 1; i >= 0; i--) { temp = dp(i, 0); if (temp <= ans) { ans = temp; r = i; } } printf ("%d", r + 1); printf_ans(r, 0); printf ("\n%d\n", ans); } return 0; }
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇V - Ice-cream Tycoon(线段树) 下一篇CodeForces 358E - Dima and Kicks

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Sphinx : 高性能SQL (2025-12-24 10:18:11)
·Pandas 性能优化 - (2025-12-24 10:18:08)
·MySQL 索引 - 菜鸟教 (2025-12-24 10:18:06)
·Shell 基本运算符 - (2025-12-24 09:52:56)
·Shell 函数 | 菜鸟教 (2025-12-24 09:52:54)