Hyperset(排序+二分)
Bees Alice and Alesya gave beekeeper Polina famous card game “Set” as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.
Polina came up with a new game called “Hyperset”. In her game, there are nn cards with kk features, each feature has three possible values: “S”, “E”, or “T”. The original “Set” game can be viewed as “Hyperset” with k=4k=4.
Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.
Unfortunately, winter holidays have come to an end, and it’s time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.
Input
The first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.
Each of the following nn lines contains a card description: a string consisting of kk letters “S”, “E”, “T”. The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.
Output
Output a single integer — the number of ways to choose three cards that form a set.
Examples
Input
3 3
SET
ETS
TSE
Output
1
Input
3 4
SETE
ETSE
TSES
Output
0
Input
5 4
SETT
TEST
EEET
ESTE
STES
Output
2
Note
In the third example test, these two triples of cards are sets:
“SETT”, “TEST”, “EEET”
“TEST”, “ESTE”, “STES”
很久沒(méi)有做算法題了,這個(gè)題不算難,但是還是手生。
首先容易想到的是O(n^3)的算法,但是一定會(huì)超時(shí)。因此我們可以固定兩個(gè),根據(jù)兩個(gè)字符串找出另一個(gè)字符串,然后判斷另外一個(gè)字符串有沒(méi)有出現(xiàn)。這樣時(shí)間復(fù)雜度就降到了O(n ^ 2),但是一開(kāi)始用的map超時(shí)了,stl畢竟耗時(shí)大。我們可以事先對(duì)字符串排個(gè)序,這樣就可以二分來(lái)找那個(gè)字符串。但是不能用SET了,要轉(zhuǎn)化成對(duì)應(yīng)的1,2,3。這樣異或起來(lái),如果是0的話,就是原來(lái)的數(shù)字,如果不是0的話,這樣就是異或之后的那個(gè)數(shù)字。排序之后二分,就可以判斷那個(gè)數(shù)字有沒(méi)有存在了。除此之外,最后的結(jié)果要除以三才是最終的答案,因?yàn)橐粯拥氖阶?#xff0c;我們找了三遍。
代碼如下:
努力加油a啊,(o)/~
總結(jié)
以上是生活随笔為你收集整理的Hyperset(排序+二分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 173. 二叉搜索树迭代器(二叉搜索树+
- 下一篇: Dr. Evil Underscores