额,简单的DFS
#include<iostream> #include<queue> using namespace std; int map[26][26]; bool vis[26][26]; struct node { int x; node(int _x=0):x(_x){}; }; bool bfs() { queue<node> Q; Q.push(node(1)); while(!Q.empty()) { node t=Q.front(); Q.pop(); for(int i=0;i<26;i++) { if(map[t.x][i]&&i=='m'-'a') return true; if(!vis[t.x][i]&&map[t.x][i]) { vis[t.x][i]=1; Q.push(node(i)); } } } return false; } int main() { char str[100]; memset(map,0,sizeof(map)); while(cin>>str) { if(strcmp(str,"0")==0) { memset(vis,0,sizeof(vis)); if(bfs()) cout<<"Yes."<<endl; else cout<<"No."<<endl; memset(map,0,sizeof(map)); continue; } int len =strlen(str); map[str[0]-'a'][str[len-1]-'a']=1; } return 0; }