发现互换的最小数目来转换一个串到另一个,其中该串可能重复字符数目、字符、最小、发现

2023-09-12 21:17:24 作者:成瘾。

我一直在寻找通过一个编程问题,当以下问题顿时显得有关。

I was looking through a programming question, when the following question suddenly seemed related.

如何使用尽可能少掉期如下您将字符串转换为另一个字符串。该字符串保证是相互转化(它们具有相同的字符集,这是送给),但是人物可以重复。我看到了同样的问题网页结果,而不会被重复,虽然人物。 在字符串中的任意两个字符可以调换。

How do you convert a string to another string using as few swaps as follows. The strings are guaranteed to be interconvertible (they have the same set of characters, this is given), but the characters can be repeated. I saw web results on the same question, without the characters being repeated though. Any two characters in the string can be swapped.

有关实例:AABBCCDD可以以两种互换转换为ddbbccaa,和ABCC可以被转换成ACCB在一个交换

For instance : "aabbccdd" can be converted to "ddbbccaa" in two swaps, and "abcc" can be converted to "accb" in one swap.

谢谢!

推荐答案

您可以构建的差异化的字符串取值 S',即包含字符的两个字符串,如的不同立场的字符串为 acbacb ABCABC 这将是 cbcb BCBC 。让我们说,这包含了n个字符。

You can construct the "difference" strings S and S', i.e. a string which contains the characters at the differing positions of the two strings, e.g. for acbacb and abcabc it will be cbcb and bcbc. Let us say this contains n characters.

您现在可以构建一个置换图G这将有 N 节点和的边缘我Ĵ如果 S [I] == S'[J] 。在所有唯一字符的情况下,很容易地看到,互换所需数量将是(正 - G中周期数),其中可以发现在O(n)的时间

You can now construct a "permutation graph" G which will have n nodes and an edge from i to j if S[i] == S'[j]. In the case of all unique characters, it is easy to see that the required number of swaps will be (n - number of cycles in G), which can be found out in O(n) time.

然而,在那里有任意数量的重复字符的情况下,这减少了找出数量最多的有向图,其中,我觉得周期的问题,是一个NP难,(如检查出: http://www.math.ucsd.edu/~jverstra/dcig.pdf)。

However, in the case where there are any number of duplicate characters, this reduces to the problem of finding out the largest number of cycles in a directed graph, which, I think, is NP-hard, (e.g. check out: http://www.math.ucsd.edu/~jverstra/dcig.pdf ).

在该文件数贪心算法指出的,其中一个是特别简单:

In that paper a few greedy algorithms are pointed out, one of which is particularly simple:

在每个步骤中,找到的最小长度周期在图中(例如,Find长度最短的有向图正权周期的) 删除它 在重复,直到所有顶点还没有被覆盖。 At each step, find the minimum length cycle in the graph (e.g. Find cycle of shortest length in a directed graph with positive weights ) Delete it Repeat until all vertexes have not been covered.

不过,有可能是利用你的案子的性质高效的算法(唯一一个我能想到的是,你的图表将成为K-三方,其中K是在独特的字符S的数量)。祝你好运!

However, there may be efficient algorithms utilizing the properties of your case (the only one I can think of is that your graphs will be K-partite, where K is the number of unique characters in S). Good luck!

编辑: 请参阅大卫的回答对问题有更全面和正确的解释。

Please refer to David's answer for a fuller and correct explanation of the problem.

 
精彩推荐
图片推荐