(BFS)
对于这个题的思路主要是BFS,从头开始分别对三个操作进行使用,直到最后需要操作的两个字符串相等或都为空,需要注意的是在两个字符串长度不等但开头的部分相等,例如A = casfg,B = ca,在这种情况下只能进行第一个操作,而对于A = ca,B = casfg,这时只能进行插入字符操作。具体代码如下:
#include <map>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <time.h>
#include <vector>
#include <list>
#include <stack>
using namespace std;
bool Flag = 0;
int result = 0,save = 0;
struct Judge {
string A, B;
int num = 0;
};
queue<Judge>store; //先进先出队列
//0代表删除字符,1代表插入字符,2代表修改一个字符
//广度优先搜索,路径数组、搜索标志数组、起始点、发现的点的数量
void BFS()
{
while (!store.empty())
{
Judge front = store.front();
if (front.A == front.B)
{
Flag = 1;
result = front.num;
//cout << "o:" << result << endl;
return;
}
if (Flag == 1)
return;
int j = 0;
while (j < front.A.length() && j < front.B.length() && front.A[j] == front.B[j])
j++;
for (int i = 0; i < 3; i++)
{
Judge Save;
if (Flag == 1)
return;
switch (i)
{
case 0:
if(j < front.A.length())
{
Save.A = front.A.substr(1 + j, front.A.length());
Save.B = front.B.substr(j, front.B.length());
Save.num = front.num + 1;
//cout << i << " 0:" << Save.num << "-" << Save.A << "-" << Save.B << endl;
store.push(Save);
}
break;
case 1:
if (j < front.B.length())
{
Save.A = front.A.substr(j, front.A.length());
Save.B = front.B.substr(1 + j, front.B.length());
Save.num = front.num + 1;
//cout << i << "1:" << Save.num << "-" << Save.A << "-" << Save.B << endl;
store.push(Save);
}
break;
case 2:
if (j < front.B.length() && j < front.A.length())
{
Save.A = front.A.substr(1 + j, front.A.length());
Save.B = front.B.substr(1 + j, front.B.length());
Save.num = front.num + 1;
//cout << i << "2:" << Save.num << "-" << Save.A << "-" << Save.B << endl;
store.push(Save);
}
break;
default:
break;
}
}
store.pop();
}
}
int main()
{
int i, j, N = 0, M;
Judge Start;
cin >> Start.A >> Start.B;
store.push(Start);
BFS();
cout << result;
//cin >> N;
return 0;
}