洛谷P1032

題目鏈接

一個比較簡單的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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章