HDU 1181 变形课 (dfs)
2014-04-04 22:35
267 查看
变形课
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submission(s): 12047 Accepted Submission(s): 4464
Problem Description
呃......变形课上Harry碰到了一点小麻烦,因为他并不像Hermione那样能够记住所有的咒语而随意的将一个棒球变成刺猬什么的,但是他发现了变形咒语的一个统一规律:如果咒语是以a开头b结尾的一个单词,那么它的作用就恰好是使A物体变成B物体.
Harry已经将他所会的所有咒语都列成了一个表,他想让你帮忙计算一下他是否能完成老师的作业,将一个B(ball)变成一个M(Mouse),你知道,如果他自己不能完成的话,他就只好向Hermione请教,并且被迫听一大堆好好学习的道理.
Input
测试数据有多组。每组有多行,每行一个单词,仅包括小写字母,是Harry所会的所有咒语.数字0表示一组输入结束.
Output
如果Harry可以完成他的作业,就输出"Yes.",否则就输出"No."(不要忽略了句号)
Sample Input
so soon river goes them got moon begin big 0
Sample Output
Yes. HintHint Harry 可以念这个咒语:"big-got-them".
建个有向图,然后DFS搜索就好。刚开始wa了好几次,最后想起link容器每次建图得清空->AC。
#include <cstdio> #include <cstdlib> #include <cstring> #include <map> #include <vector> using namespace std; map<int,vector<int> >link; bool mark; int visit[40]; void dfs(int x){ if(x=='m'-'a'){ mark = true; return; } vector<int>::iterator ite = link[x].begin(); for(;ite!=link[x].end();++ite){ if(visit[*ite]==1)continue; visit[*ite]=1;//防止绕圈 dfs(*ite); } } int main(){ char str[300]; while(1){ link.clear(); memset(visit,0,sizeof(visit)); while(1){ if(scanf("%s",str)==EOF)goto end; if(strcmp(str,"0")==0)break; link[str[0]-'a'].push_back(str[strlen(str)-1]-'a'); } mark = false; visit[1] = 1; dfs(1); if(mark){ printf("Yes.\n"); }else{ printf("No.\n"); } } end:; return 0; }
bfs的实现
#include <cstdio> #include <cstdlib> #include <cstring> #include <map> #include <vector> #include <queue> using namespace std; map<int,vector<int> >link; bool mark; int visit[40]; queue<int> que; void bfs(int x){ que.push(x); vector<int>::iterator ite; while(!que.empty()){ x = que.front(); que.pop(); if(x=='m'-'a'){ mark = true; return; } ite = link[x].begin(); for(;ite!=link[x].end();++ite){ if(visit[*ite]==1)continue; visit[*ite]=1; que.push(*ite); } } } int main(){ char str[300]; while(1){ link.clear(); memset(visit,0,sizeof(visit)); while(1){ if(scanf("%s",str)==EOF)goto end; if(strcmp(str,"0")==0)break; link[str[0]-'a'].push_back(str[strlen(str)-1]-'a'); } mark = false; visit[1] = 1; bfs(1); if(mark){ printf("Yes.\n"); }else{ printf("No.\n"); } } end:; return 0; }
相关文章推荐
- HDU 1181 变形课 DFS基础题 初学者角度+详细注释
- hdu 1181 变形课(dfs)
- HDU--1181 -- 变形课 [DFS]
- HDU 1181变形课(DFS)
- HDU 1181 变形课 (DFS)
- HDU 1181--变形课【DFS】
- hdu 1181 变形课(dfs)
- hdu 1181 变形课 dfs
- HDU 1181 变形课(连接单词串,DFS)
- HDU 1181 (DFS) 变形课
- hdu1181 变形课(vector容器+dfs)
- HDU 1181 变形课(dfs)
- hdu 题目1181 变形课 (简单DFS)
- HDU1181——变形课(dfs)
- HDU 1181 变形课(DFS)
- hdu 1181 变形课(DFS)
- (step4.3.7)hdu 1181(变形课——DFS)
- hdu 1181 变形课(dfs)
- HDU 1181 变形课(DFS)
- HDU1181 - 变形课 - 建图dfs