题目链接:
http://codevs.cn/problem/1099/
题解思路:
1.用string 类型来保存字符串 方便插入比较等操作
2.用STL set<string>来判断当前字符串是否出现过
注意字符串的下标
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<vector> #include<set> using namespace std; struct node { string str; int step; } head; struct node2 { string a,b; }; vector<node2>edge; //存边 set<string>M; void bfs(string start,string endd) { queue<node>q; M.insert(start); q.push( {start,0}); while(!q.empty()) { head=q.front(); q.pop(); if(head.str==endd) { cout<<head.step<<endl; return; } int len=head.str.length(); for(int i=0; i<edge.size(); i++) { for(int j=0; j<(int)len-(int)edge[i].a.length()+1; j++) //如果a的length()比 b的length()要小 则a.length()-b.length()结果会出错 if(edge[i].a==head.str.substr(j,edge[i].a.size())) { string d; d.append(head.str,0,j); d.append(edge[i].b); d.append(head.str,j+edge[i].a.size(),string::npos); //从j+edge[i].a.size()到末尾 全部push_back if(M.find(d)==M.end()){ //用set判重 M.insert(d); q.push({d,head.step+1}); } } } } cout<<"NO ANSWER!"<<endl; return; } int main() { string start,endd,a,b; cin>>start>>endd; while(cin>>a>>b) edge.push_back( {a,b}); bfs(start,endd); return 0; }
时间: 2024-10-16 18:52:28