这个题目,简单的搜索题,刚开始我是用并查集做的,结果很明显WA,后来想了下,如果有个单词m开头,b结尾的也可以,所以很错误的想法。运用广搜,可以很好的解决。
我的代码中的是将字符串的位置i入队的,不是整个字符串。
水题一个,下面是AC代码:
#include <iostream> #include <queue> #include <cstring> using namespace std; bool vis[1000]; char str[1000][1000]; bool flag; void bfs(int n) { queue <int> que; int a, len; for(int i = 0; i < n; i++) //将头字母为b的先入队 { if(str[i][0] == 'b') { que.push(i); vis[i] = true; } } while(!que.empty()) //进行搜索 { a = que.front(); que.pop(); len = strlen(str[a]) - 1; for(int j = 0; j < n; j++) //遍历所有字符串 { if(str[a][len] == 'm') //该字符串最后为m,说明可以完成 { flag = true; return; } if(!vis[j] && str[j][0] == str[a][len]) //将跟队列中的字符串的最后一个相同的字符串入队,并且这个字符串没有入队过的 { que.push(j); vis[j] = true; } } } } int main() { int i; i = 0; while(cin >> str[i]) { vis[i] = false; i++; if(str[i - 1][0] == '0') { vis[i] = false; flag = false; //初始化标记变量 bfs(i); if(flag) cout << "Yes." << endl; else cout << "No." << endl; i = 0; } } return 0; }
原文地址:http://blog.csdn.net/qq_25425023/article/details/45149891