Project Euler 98
Project Euler 98
题目
Anagramic squares
By replacing each of the letters in the word CARE with \(1, 2, 9\), and \(6\) respectively, we form a square number: \(1296 = 36 ^2\). What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: \(9216 = 96 ^2\). We shall call CARE (and RACE) a square anagram word pair and specify further that leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of itself).
What is the largest square number formed by any member of such a pair?
NOTE: All anagrams formed must be contained in the given text file.
解决方案
先进行两步预处理。
- 首先将所有同构的字符串放在一起,再将这些同构的字符串对处理出来。可以发现,数量大于\(1\)的类别很少。因此,经过这次预处理,同构字符串对的数量很少。
- 将所有存在自身的排列也是平方数的平方数(如\(144\)和\(441\))按照使用数位的情况分类进行存储。类似的,可以发现,数量大于\(1\)的类别也很少。
这次预处理则将大量平方数和大量字符串进行排除,方便后面筛选。
接下来,对所有同构的字符串对进行枚举。 遍历对应长度下的所有平方数,尝试按照两个同构字符串的方式,将这个平方数映射成另外一个数。最后判断答案合法性即可。
代码
1 | ls = open('p098_words.txt', 'r').readlines()[0].split(',') |