如何在1秒的时间内解决此问题?

时间:2019-12-22 03:43:36

标签: string algorithm graph-algorithm

问题:

您将获得3条替换规则,每条替换规则之间都可将一个字符串转换为另一个字符串,以及转换所必须使用的步骤数。现在,使用这些规则,您必须打印使用的规则以及到达最终字符串的规则位置。

约束

每个替换规则介于1到5个字符之间

最大步数s为15

保证可以通过规则的置换将初始字符串转换为最终字符串

样本输入

AA AB

AB BB

AA B

4 AB AAAB

示例输出:

2 1 BB

3 1 AAB

3 3 AAAA

1 3 AAAB

我尝试了使用BFS在中间相遇中进行双向搜索,该方法对 s =12。DFS在s = 6之前一直工作良好。在1s的时间限制内,是否有任何方法可以解决s = 15的问题?

""" The idea in this code is to implement bidirectional searching with meeting in the middle. Right now, the meeting part is taking around 30s, so I am not concerned about printing the steps right now. """
import math

rule = []
for k in range(3):
    rule.append(list(input().split()))

step, start, stop = input().split()
step = int(step)

level = [set() for k in range(step + 1)]
level[0].add(start)
level[step].add(stop)
histup, histdown = {}, {}
histup[start], histdown[stop] = [], []



def bfs(for_start: int, for_end: int, for_step: int, replace_this: int, replace_with: int):
    for i in range(for_start, for_end, for_step):
        for word in level[i]:  # this is the current word we are applying the rules to
            for substitution in rule:  # this contains the entire substitution
                for j in range(len(word) - len(substitution[replace_this]) + 1):
                    pos = word.find(substitution[replace_this], j)
                    if pos != -1:
                        temp = word[:pos]
                        temp += word[pos:].replace(substitution[replace_this], substitution[replace_with], 1)
                        """
                        if i == math.ceil(step / 2) + 1 and temp in level[i-1]:
                            #histdown[word].append([rule.index(substitution) + 1, pos + 1, word])
                            print(temp, '', word)
                            #print(histup[temp])
                            #print(histdown[word])
                            return
                        """
                        level[i + for_step].add(temp)

                        if for_step == 1:
                            histup[temp] = histup[word]
                            histup[temp].append([rule.index(substitution) + 1, pos + 1, temp])
                        else:
                            histdown[temp] = histdown[word]
                            histdown[temp].append([rule.index(substitution) + 1, pos + 1, word])



bfs(0, step-1, 1, 0, 1)
#bfs(0, math.floor(step / 2), 1, 0, 1)
#bfs(step, math.ceil(step / 2), -1, 1, 0)

print(level)
print(len(level[7]))

0 个答案:

没有答案