一个比较简单的DFS题,数据范围很小,直接暴力即可。
DFS问题关键的一点是剪枝,写搜索问题的时候应该自然而然地想到剪枝,并且尽可能的降低时间复杂度
几个比较常见的剪枝技巧:
1.已经超过之前的最优解,可以直接return
2.已经出现过之前的情况,可以直接return
AC代码:
/*
* @Author: hesorchen
* @Date: 2020-04-14 10:33:26
* @LastEditTime: 2020-06-20 21:24:46
* @Link: https://hesorchen.github.io/
*/
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI acos(-1)
#define PB push_back
#define ll long long
#define INF 0x3f3f3f3f
#define mod 3123456777
#define pll pair<ll, ll>
#define lowbit(abcd) (abcd & (-abcd))
#define max(a, b) ((a > b) ? (a) : (b))
#define min(a, b) ((a < b) ? (a) : (b))
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
#define FRE \
{ \
freopen("in.txt", "r", stdin); \
freopen("out.txt", "w", stdout); \
}
inline ll read()
{
ll x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
//==============================================================================
map<string, ll> mp;
string A, B;
string a[10], b[10];
ll ct = 1, ans = INF;
void dfs(string now, ll step)
{
if (mp[now]) //map剪枝
return;
mp[now] = 1;a
if (now == B)
{
ans = min(step, ans);
return;
}
if (step >= 10 || now.size() > 20)
return;
for (int i = 1; i < ct; i++)
{
ll len = a[i].size();
for (int j = 0; j + len <= now.size(); j++)
{
string tempp = now.substr(j, len);
if (tempp == a[i])
dfs(now.substr(0, j) + b[i] + now.substr(j + len), step + 1);
}
}
}
int main()
{
cin >> A >> B;
string tempa, tempb;
while (cin >> tempa >> tempb)
{
a[ct] = tempa;
b[ct++] = tempb;
}
dfs(A, 0);
if (ans != INF)
cout << ans << endl;
else
cout << "NO ANSWER!" << endl;
return 0;
}