描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
#include<iostream>
#include<vector>
#include <cmath>
#include<limits>
using namespace std;
const double eps = 0.00001;
struct mypoint
{
double x;
double y;
};
double dist(const mypoint &p1, const mypoint &p2)
{
double res = sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
return res;
}
int MaxPointinLine(const vector<mypoint> &input)
{
int len = input.size();
if (len<3)return len;
for (int i = 1; i<len;)
{
if (dist(input[0], input[i])<eps)
{
i++;
if (i == len)
return len;
}
else
break;
}
//===
int max = INT_MIN;
for (int i = 0; i<len; i++)
{
for (int j = i + 1; j<len; j++)
{
int cnt = 1;
double ratio = 0;
bool flag = false;
if (dist(input[i], input[j])<eps)
continue;
if (abs(input[i].x - input[j].x)<eps)
{
cnt++; flag = true;
}
else
{
ratio = (input[i].y - input[j].y) / (input[i].x - input[j].x);
cnt++;
}
for (int k = 0; k<len; k++)
{
if (k != i&&k != j)
{
if (dist(input[k], input[i])<eps || dist(input[k], input[j])<eps)
{
cnt++;
continue;
}
if (flag)
{
if (abs(input[k].x - input[i].x)<eps)
cnt++;
}
else
{
double ratio1 = (input[k].y - input[i].y) / (input[k].x - input[i].x);
if (abs(ratio1 - ratio)<eps)
cnt++;
}
}
}
if (cnt>max)
max = cnt;
}
}
return max;
}
int main()
{
mypoint p1 = { 1, 1 };
mypoint p2 = { 2, 2 };
mypoint p3 = { 3, 1 };
mypoint p4 = { 3, 3 };
mypoint p5 = { 3, 4 };
mypoint p6 = { 4, 1 };
mypoint p7 = { 1, 1 };
vector<mypoint> input;
input.push_back(p1);
input.push_back(p2);
input.push_back(p3);
input.push_back(p4);
input.push_back(p5);
input.push_back(p6);
input.push_back(p7);
int res = MaxPointinLine(input);
cout << res << endl;
return 0;
}