Let d[i][j] = distances between points i and j
. We are interested in a function count(i, j)
that returns, as fast as possible, the number of squares that we can draw by using points i
and j
.
Basically, count(i, j)
will have to find two points x
and y
such that d[i][j] = d[x][y]
and check if these 4 points really define a square.
You can use a hash table to solve the problem in O(n^2)
on average. Let H[x] = list of all points (p, q) that have d[p][q] = x
.
Now, for each pair of points (i, j)
, count(i, j)
will have to iterate H[ d[i][j] ]
and count the points in that list that form a square with points i
and j
.
This should run very fast in practice, and I don't think it can ever get worse than O(n^3)
(I'm not even sure it can ever get that bad).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…