题目链接
sosoonrivergoesthemgotmoonbeginbig0 Sample OutputYes.HintHint Harry 可以念这个咒语:"big-got-them". SourceGardon-DYGG Contest 1 RecommendJGShining | We have carefully selected several similar problems for you: 1175 1180 1258 1242 2553解题思路: DFS
用一个结构体数组a,a[i].x, a[i].y 分别用来存每个单词的开头和结尾, 循环查找开头为'b'的单词a[i].x == 'b',
然后DFS(s)。当a[s].x == 'm'时,找到目标查询结束,否则就继续查找以当前点的结尾为开头的i, 即a[s].y == a[i].x,继续DFS(i);
代码:
#include <cmath>#include <string>#include <cstdio>#include <sstream>#include <cstring>#include <iostream>#include <algorithm>#define LOCALusing namespace std;int n = 0;int visit[1000];int flag = 0;struct ln{ char x, y;}a[1000];void dfs(int s){ if(flag == 1) return; //提前退出以节省时间,也可不必这也写。 if(a[s].x == 'm') //目标情况 { flag = 1; return; } else { for (int i = 0; i < n; i++) if(a[s].y == a[i].x) //当前点的末尾是下个点的开始 if(!visit[i]) { visit[i] = 1; //标记走过 dfs(i); visit[i] = 0; //标记还原 } }}int main(){ string s; while (cin>>s) { //因为题目要求循环输入写的有点乱。 if(s == "0") { memset(visit, 0, sizeof(visit)); flag = 0; for(int i = 0; i < n; i++) //循环查询开头为b的然后深搜 { if(a[i].x == 'b') dfs(i); if(flag == 1) break; } if(flag) cout << "Yes." << endl; else cout << "No." << endl; n = 0; //记得将n置零 } //这里为将输入的s的开头结尾存入a中 int k = s.length(); a[n].x = s[0]; a[n].y = s[k-1]; n++; } return 0;}
新闻热点
疑难解答