File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /* ************************************************************************
2+ > File Name: OJ306字符转换.cpp
3+ > Author: ltw
4+ > Mail: 3245849061@qq.com
5+ > Github: https://github.com/hello-sources
6+ > Created Time: Wed 15 Jul 2020 09:33:10 AM CST
7+ ************************************************************************/
8+
9+ #include < iostream>
10+ #include < queue>
11+ #include < string>
12+ #include < map>
13+ using namespace std ;
14+
15+ // 搜索节点结构体,字符串,以及需要几步
16+ struct node {
17+ string str;
18+ int num;
19+ };
20+
21+ // 起点终点以及替换规则
22+ string str1, str2, rpl[7 ][2 ];
23+ queue<node> que;
24+ map<string, int > ma;// 去重
25+ int n;
26+
27+ int main () {
28+ cin >> str1 >> str2;
29+ while (cin >> rpl[n][0 ] >> rpl[n][1 ]) {
30+ n++;// 循环输入对应的替换规则
31+ }
32+ que.push ({str1, 0 });// 起点插入队列
33+ ma[str1] = 1 ;// 标记起点
34+ while (!que.empty ()) {
35+ for (int i = 0 ; i < n; i++) {// 对应n中转换规则
36+ int j = 0 ;// j代表搜索到哪里了
37+ while (1 ) {
38+ node temp2 = que.front ();
39+ long long x = temp2.str .find (rpl[i][0 ], j);// 每次找一个位置看能否替换前面字符串
40+ j = x + 1 ;
41+ if (x != string::npos) {// 找着,就替换为后面字符串
42+ temp2.str .replace (x, rpl[i][0 ].size (), rpl[i][1 ]);
43+ temp2.num ++;// 步数加一
44+ if (temp2.str == str2) {
45+ cout << temp2.num << endl;// 如果是终点直接输出
46+ return 0 ;
47+ }
48+ if (temp2.num > 10 ) continue ;// 步数超过10步,样例不要
49+ if (ma[temp2.str ] == 1 ) continue ;// 如果已经遍历,字符串也不要
50+ ma[temp2.str ] = 1 ;// 标记已经用过了
51+ que.push (temp2);// 入队
52+ } else {
53+ break ;
54+ }
55+ }
56+ }
57+ que.pop ();// 一个规则结束了,队首元素出队
58+ }
59+ cout << " NO ANSWER!" << endl;
60+ return 0 ;
61+ }
You can’t perform that action at this time.
0 commit comments