UVa 10285:Longest Run on a Snowboard(DP)
2015-09-18 20:41
369 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=848&page=show_problem&problem=1226
题意:在一个R*C(R,C≤100)(R,C \le 100)的整数矩阵上找一条高度严格递减的最长路。起点任意,但每次只能沿上下左右4个方向之一走一格,并且不能走出矩阵外。如图所示,最长路就是按照25,24,23,…,2,1这样走,长度为25。矩阵中的数均为0~100。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
dp[i][j]表示以(i,j)为终点最长能延伸多长,然后记忆化搜索即可。
代码:
题意:在一个R*C(R,C≤100)(R,C \le 100)的整数矩阵上找一条高度严格递减的最长路。起点任意,但每次只能沿上下左右4个方向之一走一格,并且不能走出矩阵外。如图所示,最长路就是按照25,24,23,…,2,1这样走,长度为25。矩阵中的数均为0~100。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
dp[i][j]表示以(i,j)为终点最长能延伸多长,然后记忆化搜索即可。
代码:
#include <iostream> #include <algorithm> #include <fstream> #include <string> #include <cstring> #include <vector> #include <queue> #include <cmath> #include <cctype> #include <stack> #include <set> #include <map> using namespace std; const int maxn = 100 + 5, INF = 1e9; const int dx[] = {0, 0, -1, 1}, dy[] = {1, -1, 0, 0}; int T, n, m, ans; int a[maxn][maxn], dp[maxn][maxn]; char s[maxn]; int DP(int x, int y) { if (dp[x][y] > 0) return dp[x][y]; dp[x][y] = 1; for (int i = 0; i < 4; ++i) { int xx = x + dx[i], yy = y + dy[i]; if (xx >= 0 && xx < n && yy >= 0 && yy < m) { if (a[x][y] > a[xx][yy]) dp[x][y] = max(dp[x][y], DP(xx, yy) + 1); } } return dp[x][y]; } int main() { scanf("%d", &T); for (int C = 0; C < T; ++C) { ans = 1; scanf("%s%d%d", s, &n, &m); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) scanf("%d", &a[i][j]); memset(dp, -1, sizeof(dp)); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) ans = max(ans, DP(i, j)); printf("%s: %d\n", s, ans); } return 0; }
相关文章推荐
- c++内部类
- Java管理对象神奇之Object类的equals和hashcode
- Linux虚拟机fdisk分区
- linux下C语言socket网络编程简例
- 控制器显示细节
- TCP/IP协议原理与应用笔记04:子网掩码
- 【UI初级--连载五】---------UIViewController(视图控制器)
- 九九乘法表
- Socket编程(c语言示例)
- 【leetcode】No.154 Find Minimum in Rotated Sorted Array II
- General Problem Solving Techniques [Beginner-1]~E
- sqlite特性 只能添加字段 不能修改字段 的解决方法 和php sqlite的管理工具 sqlbuddy
- 揭开HashCode()和equals()的面纱
- ORACLE数据库性能优化之-->内存磁盘
- jQuery在线学习,相对比较全,推荐给那些初学者
- 求三角形、矩形、圆的面积
- 远程推送
- 职场新人完全转型七大要素
- 从数据库取出被 特殊符号被转义实体后的数据
- 重学C++Primer笔记3---一开始就要有好的习惯