#include "iostream"
#include "string"
#include "vector"
#include "stack"
#include "cstring"
#define already 1
using namespace std;
vector<string> word;
vector<int> a[10000];
bool dps(int i ,int s){
stack<int> st;//存输入的顺序序号
int color[s];
memset(color,-1,sizeof(color));
color[i] = already;
st.push(i);
while(!st.empty()){
int u = st.top(); st.pop();
for(int j = 0; j < a[u].size(); j++){
int v = a[u][j];
if(color[v] == -1) {
color[v] = already;
if(*(word[v].end()-1) == 'm') return true;
else{
st.push(v);
}
}
}
}
return false;
}
int main(){
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
string n;
int s = 0;
bool flag = false;
while(cin >> n ){
if(n!="0"){
word.push_back(n); //s计数
s++;
while(cin >> n && n!="0"){
word.push_back(n);
s++;
}
for (int i = 0; i < s ; i++){
for (int j = 0; j < s; j++){
if(*(word[j].begin()) == *(word[i].end()-1) && i != j)
a[i].push_back(j); //只保存序号
}
}
for (int i = 0; i < s; i++){
if(*(word[i].begin()) == 'b'){
flag = dps(i,s);
}
}
if (flag == true ) cout << "Yes." << endl;
else cout << "No." << endl;
}
word.clear();
for(int i = 0; i < 10000; i++) a[i].clear();
s = 0;
flag = false;
}
return 0;
}
本题是初学DPS而做,花了近2个小时时间才完成,比较low,但是收获还是挺大的,比如记录word的序号,还有string的进一步使用,进一步熟练了输入输出和vector。本题总体不难,就是一个深度优先搜索。
下面是DFS的递归写法,也是推荐写法
#include "iostream"
#include "string"
#include "vector"
#include "cstring"
#define already 1
using namespace std;
bool flag = false;
int color[10000];
vector<string> word;
vector<int> a[10000];
int s;
void dps(int i ){
if(flag == 1) return ;
if(color[i] == -1){
color[i] = already;
if(*(word[i].end()-1) == 'm') {
flag = 1;
}
else{
for(int j = 0; j < a[i].size(); j++){
int v = a[i][j];
dps(v);
}
}
}
}
int main(){
//
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
//
string n;
while(cin >> n ){
if(n!="0"){
word.push_back(n); //s计数
s++;
while(cin >> n && n!="0"){
word.push_back(n);
s++;
}
for (int i = 0; i < s ; i++){
for (int j = 0; j < s; j++){
if(*(word[j].begin()) == *(word[i].end()-1) && i != j)
a[i].push_back(j); //只保存序号
}
}
for (int i = 0; i < s; i++){
if(*(word[i].begin()) == 'b'){
memset(color,-1,sizeof(color));
dps(i);
}
}
if (flag == true ) cout << "Yes." << endl;
else cout << "No." << endl;
}
word.clear();
for(int i = 0; i < 10000; i++) a[i].clear();
s = 0;
flag = false;
}
return 0;
}