词排名效率

时间:2014-06-03 21:37:23

标签: permutation combinatorics

我不确定如何在约束内解决这个问题。

考虑一个"字"任何大写字母序列A-Z(不仅限于"词典单词")。对于具有至少两个不同字母的任何单词,还有其他单词由相同的字母组成,但顺序不同(例如,STATIONARILY / ANTIROYALIST,它们都是字典单词;为了我们的目的" AAIILNORSTTY&#34 ;也是一个"字"由与这两个字母相同的字母组成)。然后,我们可以根据每个单词的位置为每个单词分配一个数字,该单词位于由同一组字母组成的所有单词的按字母顺序排序的列表中。一种方法是生成整个单词列表并找到所需单词,但如果单词很长,这将会很慢。编写一个程序,它将一个单词作为命令行参数,并将其编号打印到标准输出。不要使用上面生成整个列表的方法。你的程序应该能够接受25个字母或更少的字母(可能重复一些字母),并且应该使用不超过1 GB的内存并运行不超过500毫秒。我们检查的任何答案都适合64位整数。

示例单词及其等级:

ABAB = 2 
AAAB = 1 
BAAA = 4 
QUESTION = 24572 
BOOKKEEPER = 10743

的示例:

AAAB - 1
AABA - 2
ABAA - 3
BAAA - 4

AABB - 1
ABAB - 2
ABBA - 3
BAAB - 4
BABA - 5
BBAA - 6

我考虑过使用二进制搜索单词和所有可能由单词构建的单词(1 - 置换(单词)),但我认为这需要太长时间。 O(logN)可能太慢了。

我找到了这个解决方案,但我有点困惑,需要一些帮助来理解它:

Consider the n-letter word { x1, x2, ... , xn }. My solution is based on the idea that the word number will be the sum of two quantities:

The number of combinations starting with letters lower in the alphabet than x1, and
how far we are into the the arrangements that start with x1.
The trick is that the second quantity happens to be the word number of the word { x2, ... , xn }. This suggests a recursive implementation.

Getting the first quantity is a little complicated:

Let uniqLowers = { u1, u2, ... , um } = all the unique letters lower than x1
For each uj, count the number of permutations starting with uj.
Add all those up.

1 个答案:

答案 0 :(得分:2)

解决方案说答案由两个数字组成。请看下面的图片,描述可以从单词QUESTION中获得的单词:

EIONQSTU (first word lexographically, rank 1)
...
...
... (first word before Q, rank A)
QEIONSTU 
....
....
QUESTION (our given word, rank x)
...

这句话"我们进入以x1"开头的安排,是数量(xA),称之为B.事物是B完全等于&#的单词等级34; UESTION",这是我们原来的第一个字母切断的字。这是问同样的问题,但我们的输入的一个子集,建议递归解决方案。

然后仍然找到A,这表示找到以Q之前的单词开头的单词的排列数。所以A =以{E,I,O,N}开头的单词数