POJ 1204Word Puzzles 字典树
来源:互联网 发布:get it right 编辑:程序博客网 时间:2024/06/05 19:56
http://poj.org/problem?id=1204
题意:先给出字母矩阵,然后给出几个单词,要求输出这几个单词在矩阵中的起始位置及方向。
思路:刚看这道题就被输出吓到了,后来才发现根本没那么吓人。
先用给出的几个单词创建一棵字典树,然后在矩阵中每一个字母的每一个方向查找字典树中的单词,然后记录最初的起点和方向就OK了。
注意:刚开始做这题的思想是利用字母矩阵创建字典树,后来觉得难度太大(也许根本行不通)。上网找资料才发现原来是利用给出的单词来创建字典树。还需要注意的就是一些细节方面的处理,下面代码注释中给出。
#include<iostream>#include<cstdio>#include<queue>#include<cstring>#include<string>#include<cmath>#include<algorithm>#include<stdlib.h>#include<stack>#include<vector>#include<map>#define maxn 1<<29#define pi acos(-1.0)typedef long long LL;using namespace std;int h,l,n;char mmap[1010][1010];char word[1010][1010];int tx[]={0,1,1,1,0,-1,-1,-1};int ty[]={1,1,0,-1,-1,-1,0,1};int ch[200010][27];int sz;int val[200010];struct node{ int x; int y; int d; int flag;}xun[200010]; //用来保存起始点和方向void init(){ sz=1; memset(ch,0,sizeof(ch)); memset(val,0,sizeof(val));}void insert(char *s){ int u=0,c; for(int i=0;i<strlen(s);i++) { c=s[i]-'a'; if(!ch[u][c]) ch[u][c]=sz++; u=ch[u][c]; // val[u]++; } val[u]=1; //这样在单词的结尾标记可能会好些}int inside(int x,int y){ if(x>=0&&x<h&&y>=0&&y<l) return 1; return 0;}int solve(int h,int l,int k){ int xx=h; //记录初始坐标 int yy=l; int u=0,c; while(inside(h,l)) { c=mmap[h][l]-'a'; if(!ch[u][c]) return 0; u=ch[u][c]; if(val[u]==1) { xun[u].x=xx; //把初始坐标和方向记录下 xun[u].y=yy; xun[u].d=k; xun[u].flag=1; // return 0; 这里不要有,当第一个是第二个前缀的情况下, // 找到第一个就直接退出,找不到第二个 } h+=tx[k]; l+=ty[k]; } return 0;}int main(){ init(); //当输出只有一个不对的时候考虑下初始化 cin>>h>>l>>n; for(int i=0;i<h;i++) scanf("%s",mmap[i]); for(int i=0;i<n;i++) { scanf("%s",word[i]); insert(word[i]); } for(int i=0;i<h;i++) { for(int j=0;j<l;j++) { for(int k=0;k<8;k++) { solve(i,j,k); //遍历矩阵 } } } char targ[]={"ABCDEFGH"}; for(int i=0;i<200010;i++) { if(xun[i].flag==1) //这里方向不知道出了什么问题,总是少了2个单位,所以就直接加回来了 printf("%d %d %c\n",xun[i].x,xun[i].y,targ[(xun[i].d+2)%8]); } return 0;}
0 0
- poj 1204 Word Puzzles 字典树
- poj 1204 Word Puzzles(字典树)
- poj 1204 Word Puzzles 字典树 + 暴搜
- POJ 1204Word Puzzles 字典树
- 字典树+DFS Word Puzzles POJ 1204
- poj 1204 Word Puzzles(字典树)
- POJ 1204 Word Puzzles // 字典树,枚举, 搜索
- 字典树PKU 1204 Word Puzzles
- poj 1204 Word Puzzles
- poj 1204 Word Puzzles
- poj 1204 Word Puzzles
- POJ-1204-Word Puzzles
- poj 1204 Word Puzzles
- poj 1204 Word Puzzles
- 【POJ】1204 Word Puzzles
- 【字典树】poj 1204 Word Puzzles(外:poj Shortest Prefixes)
- 【字典树】 poj1204 Word Puzzles
- POJ1204 - Word Puzzles - 字典树
- WebSphere Message Broker(2)--WMB V8下载、安装
- 安卓----fragment与动画
- Cocos2d-x设计模式发掘之二:二段构建模式
- select, poll和epoll (ZZ)
- 容器框架的探索思绪日记
- POJ 1204Word Puzzles 字典树
- 如何防止客户端被破解
- 02-3. 逆序的三位数(10)
- The War
- OpenCV学习C++接口 Mat像素遍历详解
- poj 2411 编程之美-瓷砖覆盖地板
- 拓扑排序Sorting It All Out
- 求解 :在最后为什么输出的整形数字是-858993460,,应该不是溢出错误
- POJ 1258 Agri-Net最小生成树 prim