Given a list of coordinates in the first quadrant, calculate how many right triangles can be formed which have one side parallel to x-axis
Given a list of coordinates in the first quadrant
, calculate how many right triangles can be formed from these which have one side parallel to x-axis
and one side parallel to y-axis
.
Recently I took part in a programming competition, more specifically INOI(Indian National Olympiad n Informatics) and this was the first out of two questions in the paper开发者_运维知识库.
Basically I figured any 3 points of type (a,y)
(x,y)
(x,b)
would form such a triangle but couldn't manage anything better, and in the end just wrote a naive O(n^3) solution (and so did all my friends).
Can anyone suggest a better way?
And please, THIS IS NOT HOMEWORK.
Lets numX[i] = how many points have i as their X coordinate
and numY[i] = how many points have i as their Y coordinate
.
We will count how many triangles with the required property exist for a certain point p
. Without loss of generality, we can assume that p
is the point where the triangles make their right angle.
For this to happen, we need a point with the same Y
coordinate and one with the same X
coordinate. So how about this algorithm:
compute numX and numY in O(n).
num = 0
for each point p in the given list of points
num += (numX[p.X] - 1)*(numY[p.Y] - 1)
output num
Basically, we can combine each point with the same X
coordinate with each point with the same Y
coordinate to get the required triangle. We subtract 1
so as not to count p
itself.
This will run in O(n)
.
Yeah, I agree with IVlad there. the input can be directly stored in a 2*N array, and at the same time the count for every x and y should be stored in numX and numY... then it's just wat IVlad said...
精彩评论