sanchit.h
sanchit.h

Reputation: 134

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.

Upvotes: 3

Views: 1748

Answers (2)

asdofindia
asdofindia

Reputation: 149

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...

Upvotes: 2

IVlad
IVlad

Reputation: 43477

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).

Upvotes: 5

Related Questions