牛客 处女座与复读机(搜索)

最近是怎么了… 稍微带点拐弯的搜索都不会写了…
这题很简单呀…略微转换一下思想, 我们定义搜索状态为s1中的a位置和s2中的b位置, 终点是as1.size(), bs2.size(), 对于增加, 删除, 改变, 因为我们一定使得改动之后的s1[a]==s2[b], 所有可以等价理解为对a, b的改动

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const LL maxn = 1e6+10;

string s1, s2;
bool flag = false;
void Dfs(int a, int b, int cont)
{
    //搜索s1串第a个字符和s2串第b个字符的状态
    if(cont > 2) return;
    if(a==s1.size() && b==s2.size()) {flag = true; return;}
    
    if(s1[a] == s2[b]) Dfs(a+1, b+1, cont); //相等直接跳过
    else{
        Dfs(a+1, b, cont+1);     //添加
        Dfs(a+1, b+1, cont+1);   //修改
        Dfs(a, b+1, cont+1);     //删除
    }
}
int main()
{
    
    cin >> s1 >> s2;
    Dfs(0, 0, 0);
    
    if(flag) cout << "YES" << endl;
    else cout << "NO" << endl;

	return 0;
}

相关文章: