习题7-15:最大的数(dfs+最优性剪枝)
来源:互联网 发布:java 打印内存地址 编辑:程序博客网 时间:2024/05/07 00:00
习题7-15:最大的数
题意:
在一个R行C列(2≤R,C≤15,R∗C≤30)的矩阵里有障碍物和数字格(包含1~9的数字)。
你可以从任意一个数字格出发,每次沿着上下左右之一的方向走一格,但不能走到障碍格中,也不能重复经过一个数字格,然后把沿途经过的所有数字连起来,如图所示。如图可以得到9784,4832145等整数。问:能得到的最大整数是多少?(本段摘自《算法竞赛入门经典(第2版)》)
解题思路:
枚举起点进行DFS即可。有一个最优性剪枝,即当当前位置的时候,剩下可以走的最大长度加上已走长度如果仍然小于当前最优的答案时,直接return,如果相等但是字典序比当前最优答案小的话也直接return。
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<string>#include<cmath>#include<set>#include<queue>#include<map>#include<stack>#include<vector>#include<list>#include<deque>using namespace std;typedef long long ll;int dir[4][2] = {1,0,0,1,-1,0,0,-1};const int maxn = 1e6 + 10;const double eps = 1e-6;const int INF = 1 << 30;int n, m;string ans;char Map[50][50];bool v[50][50], vv[50][50];struct node{ int x, y;};void update(const string& s){ int l1 = ans.size(); int l2 = s.size(); if((l1 < l2) || ((l1 == l2) && s > ans))ans = s;}node q[500];int deep(int x, int y){ int head = 0, tail = 0, cnt = 0; q[tail].x = x; q[tail++].y = y; memcpy(vv, v, sizeof(v)); while(head != tail) { for(int i = 0; i < 4; i++) { int xx = q[head].x + dir[i][0], yy = q[head].y + dir[i][1]; if(xx >= 0 && xx < n && yy >= 0 && yy < m && isdigit(Map[xx][yy]) && !vv[xx][yy]) { q[tail].x = xx; q[tail++].y = yy; vv[xx][yy] = 1; cnt++; } } head++; } return cnt;}void dfs(int x, int y, string s, int d){ int l = deep(x, y); //cout<<l<<endl; if(d + l < ans.size())return ; if(d + l == ans.size() && (s + "z") < ans)return; update(s); //cout<<ans<<endl; for(int i = 0; i < 4; ++i) { int xx = x + dir[i][0]; int yy = y + dir[i][1]; if(xx >= 0 && xx < n && yy >= 0 && yy < m && isdigit(Map[xx][yy]) && !v[xx][yy]) { v[xx][yy] = 1; dfs(xx, yy, s + Map[xx][yy], d + 1); v[xx][yy] = 0; } }}int main(){ while(scanf("%d%d",&n, &m)) { ans = "";///初始化要记得 if(!n && !m)break; for(int i = 0; i < n; i++) { cin >> Map[i]; } string tmp; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(isdigit(Map[i][j])) { memset(v, 0, sizeof(v)); v[i][j] = 1; tmp = ""; tmp += Map[i][j]; dfs(i, j, tmp, 1); } } } cout<<ans<<endl; } return 0;}
阅读全文
0 0
- 习题7-15:最大的数(dfs+最优性剪枝)
- HDU 4848-Wow! Such Conquering!(DFS+最优性剪枝)
- D. Lizards and Basements 2 (DFS+最优性剪枝)
- HDU 4848-Wow! Such Conquering!(DFS+最优性剪枝)
- 习题7-15 最大的数 UVa11882
- UVa140 - Bandwidth DFS最优性剪枝题
- Poj 1724 Roads(DFS 可行性剪枝 最优性剪枝 向量)
- Uva11882 Biggest Number 【dfs回溯+bfs剪枝】【习题7-15】
- Uva307 Sticks 【dfs+剪枝】【习题7-14】
- hdu 4090 GemAnd Prince dfs+bfs+最优性剪枝
- [NOIP 2003] 传染病控制:创造性地DFS,最优性剪枝
- uva140_dfs(回溯)最优性剪枝
- Uva140 最优性剪枝
- 习题7-8:数字谜(dfs暴搜)
- 同时寻找最大数和最小数的最优算法
- 同时寻找最大数和最小数的最优算法
- 51nod 1060 最复杂的数 数学&dfs剪枝
- 习题7-1 uva 208(剪枝)
- Microsoft Virtual PC2007的安装配置
- poj题目清单(一)
- 实验二 线性表综合实验——单链表
- push was rejected by remote(因部分文件过大)(安卓)
- PL/SQL之四 触发器
- 习题7-15:最大的数(dfs+最优性剪枝)
- 802.1Q帧格式
- Windows环境下MongoDB的安装与简单的命令
- Linux中文件文档的基本操作命令
- 第一次的博客
- 《堪萨斯》:记忆、自我与向善
- 275. H-Index II
- windows配置spark运行环境
- Java8中Lambda表达式学习