This problem is from the recently concluded Facebook Hackercup 2016 Qualification round. You can take a look at the problem statement in this link.
I am giving the abridged problem statement here. Given a set of coordinates in a 2D-plane, We have to find out the total number of pairs of lines with equal length and also share one end point.
For example, let us take the points {(0,0), (0,1), (1,0)}
, there is one pair of lines, with a distance of 1. The line between (0,0), (0,1)
and the line between (0,0), (1,0)
.
The simplest way to solve this problem is this. Take a point (x,y) and try to calculate the distance to every other point. Maintain a map of distance to the number of other end points with that distance. This is O(n2 log n) solution.
Here is the C++ code for the same.
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <map> | |
using namespace std; | |
int main() | |
{ | |
int t; | |
cin >> t; | |
for( int tc = 0; tc < t; tc++) | |
{ | |
int n; | |
cin >> n; | |
int i, j; | |
vector<pair<int,int> > pairs(n); | |
for( i = 0; i < n; i++ ) | |
{ | |
int x,y; | |
cin >> x >> y; | |
pairs[i] = make_pair(x,y); | |
} | |
long long res = 0; | |
map<int, int> dmap; | |
for( i = 0; i < n; i++ ) | |
{ | |
dmap.clear(); | |
for( j = 0; j < n; j++ ) | |
{ | |
if( i != j ) | |
{ | |
int d = (pairs[i].first-pairs[j].first)*(pairs[i].first-pairs[j].first) + | |
(pairs[i].second-pairs[j].second)*(pairs[i].second-pairs[j].second); | |
res += dmap[d]; | |
dmap[d]++; | |
} | |
} | |
} | |
cout << "Case #" << (tc+1) << ": " << res<< endl; | |
} | |
return 0; | |
} |