标签:bfs 做了 margin cin return otto tmp 变换 span
题目链接为:https://www.luogu.org/problemnew/show/P1032
思路:看到数据比较小,而且最多有6个规则,就可以用搜索去做了,我用的BFS,大体思路如下:
下面是AC代码:
1 #include<cstdio> 2 #include<string> 3 #include<queue> 4 #include<iostream> 5 #include<map> 6 using namespace std; 7 8 struct node{ 9 string str; 10 int num; 11 }nod; 12 13 queue<node> q; 14 map<string,int> m; 15 string a,b; 16 string aa[6],bb[6]; 17 int n=0; 18 19 void bfs(){ 20 q.push(nod); 21 while(!q.empty()){ 22 node now=q.front();q.pop(); 23 string ns=now.str; 24 int nn=now.num; 25 if(nn>10){ 26 printf("NO ANSWER!\n"); 27 return; 28 } 29 if(ns==b){ 30 printf("%d\n",nn); 31 return; 32 } 33 for(int i=0;i<n;i++){ 34 int index=ns.find(aa[i],0); 35 while(index!=string::npos){ 36 string tmp=ns; 37 tmp.replace(index,aa[i].length(),bb[i]); 38 if(!m[tmp]){ 39 m[tmp]=1; 40 nod.str=tmp; 41 nod.num=nn+1; 42 q.push(nod); 43 } 44 index=ns.find(aa[i],index+aa[i].length()); 45 } 46 } 47 } 48 printf("NO ANSWER!\n"); 49 } 50 51 int main(){ 52 cin>>a>>b; 53 while(cin>>aa[n]>>bb[n]) 54 n++; 55 nod.str=a; 56 nod.num=0; 57 m[a]=1; 58 bfs(); 59 return 0; 60 }
标签:bfs 做了 margin cin return otto tmp 变换 span
原文地址:https://www.cnblogs.com/FrankChen831X/p/10327449.html