#include<iostream> #include<cstring> #include<string> #include<queue> using namespace std; struct words{ char start; char end; }word[100005]; int vis[100005]; int main() { string str; while(cin>>str) { int cnt = 0; if(str[0]!='0') { word[cnt].start = str[0]; word[cnt].end = str[str.length()-1]; cnt++; } while(cin>>str) { if(str[0]=='0') break; word[cnt].start = str[0]; word[cnt].end = str[str.length()-1]; cnt++; } queue<words> Q; for(int i = 0;i<cnt;i++) { if(word[i].start=='b') { Q.push(word[i]); vis[i] = 1; } } words tmp; while(!Q.empty()) { tmp = Q.front(); Q.pop(); if(tmp.end=='m') { cout<<"Yes."<<endl; break; } for(int i = 0;i<cnt;i++) { if(!vis[i]&&word[i].start==tmp.end) { Q.push(word[i]); vis[i] = 1; } } } if(tmp.end!='m') { cout<<"No."<<endl; } } return 0; }
思路:每个字符串有用的只有第一个字符和最后一个字符有用,只需要记录这两个字符。然后从以b开头入队,BFS,直到找到结尾为m的为止,搜索过程中用一个vis数组记录单词是否已经被搜索过,避免出现重复入队造成无限循环。
浙公网安备 33010602011771号