洛谷 P1032 字串变换
来源:互联网 发布:杭州软件测试培训班 编辑:程序博客网 时间:2024/06/06 02:38
题目描述
已知有两个字串 A, B 及一组字串变换的规则(至多6个规则):
A1 -> B1
A2 -> B2
规则的含义为:在 A$中的子串 A1 可以变换为 B1、A2 可以变换为 B2 …。
例如:A=’abcd’B=’xyz’
变换规则为:
‘abc’->‘xu’‘ud’->‘y’‘y’->‘yz’
则此时,A 可以经过一系列的变换变为 B,其变换的过程为:
‘abcd’->‘xud’->‘xy’->‘xyz’
共进行了三次变换,使得 A 变换为B。
输入输出格式
输入格式:
键盘输人文件名。文件格式如下:
A B A1 B1 \
A2 B2 |-> 变换规则
… … /
所有字符串长度的上限为 20。
输出格式:
输出至屏幕。格式如下:
若在 10 步(包含 10步)以内能将 A 变换为 B ,则输出最少的变换步数;否则输出”NO ANSWER!”
输入输出样例
输入样例#1:
abcd xyz
abc xu
ud y
y yz
输出样例#1:
3
由题解可知:双向bfs。
再知道stl函数replace和find就可以了。
#include<iostream>#include<cstdio>#include<string>#include<queue>#include<map>using namespace std;string a,b,ch[11][2];int n=1;queue<string>q1,q2;map<string,int>visa,visb;void bfs(){ visa[a]=1,visb[b]=1; q1.push(a),q2.push(b); while(1) { if(q1.empty()||q2.empty()) { printf("NO ANSWER!\n"); return ; } string ta=q1.front(),tb=q2.front(); if(visa[ta]>11||visb[tb]>11) { printf("NO ANSWER!\n"); return ; } for(int i=1;i<=n;i++) { int k=0; while(ta.find(ch[i][0],k)!=-1) { k=ta.find(ch[i][0],k); int l=ch[i][0].length(); ta.replace(k,l,ch[i][1]); if(visa[ta]==0) { visa[ta]=visa[q1.front()]+1; q1.push(ta); } if(visb[ta]!=0&&visa[ta]+visb[ta]-2<=10) { printf("%d\n",visa[ta]+visb[ta]-2); return ; } k++; ta=q1.front(); } } for(int i=1;i<=n;i++) { int k=0; while(tb.find(ch[i][1],k)!=-1) { k=tb.find(ch[i][1],k); int l=ch[i][1].length(); tb.replace(k,l,ch[i][0]); if(visb[tb]==0) { visb[tb]=visb[q2.front()]+1; q2.push(tb); } if(visa[tb]!=0&&visa[ta]+visb[ta]-2<=10) { printf("%d\n",visa[tb]+visb[tb]-2); return ; } k++; tb=q2.front(); } } q1.pop(),q2.pop(); }}int main(){ cin>>a>>b; while(cin>>ch[n][0]>>ch[n][1]) ++n; --n; bfs(); return 0;}
0 0
- 洛谷 P1032 字串变换
- 洛谷 P1032 字串变换
- 洛谷 P1032 字串变换
- 洛谷 P1032 字串变换
- 洛谷 P1032 字串变换
- [抄]洛谷 P1032 字串变换
- 洛谷P1032&NOIP2002 字串变换
- 洛谷p1032字串变换c++
- 洛谷 P1032 [NOIP2002 T2] 字串变换
- P1032 字串变换
- BFS之P1032 字串变换
- 双向bfs——洛谷P1032 字串变换
- 洛谷1032 字串变换
- 【洛谷 1032】 字串变换
- 洛谷1032 字串变换
- 洛谷 1032 字串变换
- 【p1032-子串变换】解题记录
- 字串变换
- linux中rar文件解压缩的实现
- java 图的深度遍历 邻接矩阵
- struts2防止重复提交
- git .gitignore生效解决方案
- oracle创建用户导入导出
- 洛谷 P1032 字串变换
- weblogic性能调优
- 阿里云CentOS7.264位下Node.js环境部署
- ViewPager + Fragment实现滑动标签页
- Android热修复原理
- eclipse下保证jdbc以SQL身份验证方式连接SQL Server2008数据库
- instanceof 和原型链
- EasyUI问题总结
- 关于display:inline-block