#5超时了,求助大佬提供剪枝思路
查看原帖
#5超时了,求助大佬提供剪枝思路
383198
xwfro楼主2024/9/4 08:08
#include <algorithm>
#include <cstring>
#include <deque>
#include <iostream>

std::string change[50][2];
std::string start;
std::string end;
std::string s_cin;
int index_1 = 0;
int ans = 11;
std::deque<std::pair<std::string, int>> dq;

void replaceSubstr(const std::string &str, const std::string &target, const std::string &replacement, int start, int time)
{
    // 在str中从start位置查找target子串
    size_t pos = str.find(target, start);

    // 如果找到target子串
    if (pos != std::string::npos)
    {
        // 替换该子串
        std::string newStr = str;
        newStr.replace(pos, target.length(), replacement);

        // 新的字符串和步数入队
        dq.push_back(std::make_pair(newStr, time + 1));

        // 继续递归替换下一个子串
        replaceSubstr(str, target, replacement, pos + 1, time);
    }
}

void bfs()
{
    while (!dq.empty())
    {
        std::string s = dq.front().first;
        int num = dq.front().second;
        dq.pop_front();

        if (s == end)
        { // 如果找到了目标字符串
            ans = std::min(ans, num);
            break;
        }
        if (num > 10)
            break;
        for (int i = 0; i < index_1; i++)
        {
            replaceSubstr(s, change[i][0], change[i][1], 0, num);
        }
    }
}

int main()
{
    std::cin >> start >> end;

    while (std::cin >> change[index_1][0] >> change[index_1][1])
    {
        index_1++;
    }

    dq.push_back(std::make_pair(start, 0)); // 初始状态入队
    bfs();

    if (ans > 10) // 如果没有找到解
        std::cout << "NO ANSWER!";
    else
        std::cout << ans;

    return 0;
}

2024/9/4 08:08
加载中...