dp学习之AvoidRoads解法二(算法优化)
2016-04-16 21:47
465 查看
在上一篇AvoidRoads解法中,虽然能得到正确的答案但存在很大的瑕疵,比如需要分三种情况:
第一种 x>0,y=0
第二种 x=0,y>0
第三种 x>0,y>0
程序分完这三种情况后显得很长,因此有必要进行优化。
优化源代码如下(c++):
第一种 x>0,y=0
第二种 x=0,y>0
第三种 x>0,y>0
程序分完这三种情况后显得很长,因此有必要进行优化。
优化源代码如下(c++):
#include <iostream> #include <vector> #include <cstdio> #include <string> #include <cstring> #include <sstream> using namespace std; int dx[] = {1, 0}; int dy[] = {0, 1}; class AvoidRoads { public: long long numWays(int width, int height, vector<string> &bad); }; int main(void) { AvoidRoads l; vector<string> str; #if 0 str.push_back("0 3 0 2"); str.push_back("1 2 1 3"); str.push_back("2 2 2 3"); str.push_back("3 2 3 3"); str.push_back("4 2 4 3"); str.push_back("5 2 5 3"); str.push_back("6 2 6 3"); str.push_back("7 2 7 3"); str.push_back("8 2 8 3"); str.push_back("9 2 9 3"); #endif str.push_back("0 0 0 1"); str.push_back("6 6 5 6"); cout << l.numWays(6, 6, str) << endl; return 0; } long long AvoidRoads::numWays(int width, int height, vector<string> &bad) { long long D[width + 1][height + 1]; char is_bad1[128], is_bad2[128]; for(int i = 0; i <= width; i++) { for(int j = 0; j <= height; j++) { D[i][j] = 0; } } D[0][0] = 1; for(int i = 0; i <= width; i++) { for(int j = 0; j <= height; j++) { for(int k = 0; k < 2; k++) { int is_bad = 0; int tx = i + dx[k]; int ty = j + dy[k]; #if 1 /*If you know why the next two line is needful, you are so clever*/ if(tx > width || ty > height) continue; #endif snprintf(is_bad1, sizeof(is_bad1), "%d %d %d %d", i, j, tx, ty); snprintf(is_bad2, sizeof(is_bad2), "%d %d %d %d", tx, ty, i, j); for(int p = 0; p < bad.size(); p++) { if(bad[p] == string(is_bad1) || bad[p] == string(is_bad2)) { is_bad = 1; break; } } if(is_bad != 1) { D[tx][ty] += D[i][j]; } } } } return D[width][height]; }
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- MySQL 优化
- 如何写好 C main 函数
- 书评:《算法之美( Algorithms to Live By )》
- Google排名优化的几个影响因素
- 动易2006序列号破解算法公布
- DB2优化(简易版)
- Mysql limit 优化,百万至千万级快速分页 复合索引的引用并应用于轻量级框架
- C#中尾递归的使用、优化及编译器优化
- 对优化Ruby on Rails性能的一些办法的探究
- 优化Ruby脚本效率实例分享
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua和C语言的交互详解
- Asp编码优化技巧
- 如何监测和优化OLAP数据库
- mysql -参数thread_cache_size优化方法 小结
- 深入学习SQL Server聚合函数算法优化技巧
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二