15.15—细节实现题—Max Points on a 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值