二位平面上,经过点数最多的线

#include<iostream>
#include<vector>
#include<math.h>
#include<hash_map>
using namespace std;
class Point{
public:
	double x;
	double y;
	Point() :x(0.0), y(0.0){}
	Point(double _x, double _y) :x(_x), y(_y){}
};

class Line{
private:
	bool infinite_slope = false;
public:
	double epsilon = 0.0001;
	double slope;
	double intercept;

	Line(){}

	Line(Point p1, Point p2){
		if (fabs(p1.x - p2.x) > epsilon){
			slope = (p1.y - p2.y) / (p1.x - p2.x);
			intercept = p1.y - slope*p1.x;
		}
		else{
			infinite_slope = true;
			intercept = p1.x;
		}
	}

	double floorToNearestEpsilon(double d){
		int r = (int)(d / epsilon);
		return ((double)r)*epsilon;
	}

	bool isEquivalent(double a, double b){ return fabs(a - b) < epsilon; }

	bool isEquivalent(Line& l){
		if (isEquivalent(l.slope, slope) && isEquivalent(l.intercept, intercept) && (infinite_slope == l.infinite_slope))
			return true;
		return false;
	}


};

int countEquivalentLines(vector<Line> lines, Line line){
	if (lines.size() == 0) return 0;
	int count = 0;
	for (int i = 0; i < (int)lines.size(); ++i)
		if (lines[i].isEquivalent(line))
			++count;
	return count;
}

int countEquivalentLines(hash_map<double, vector<Line>> lineBySlope, Line line){
	double key = line.floorToNearestEpsilon(line.slope);
	int count = countEquivalentLines(lineBySlope[key], line) + 
		countEquivalentLines(lineBySlope[key - line.epsilon],line) + 
		countEquivalentLines(lineBySlope[key + line.epsilon],line);
	return count;
}

void insertLine(hash_map<double, vector<Line>>& lineBySlope, Line& line){
	vector<Line> v;
	double key = line.floorToNearestEpsilon(line.slope);
	hash_map<double, vector<Line>>::iterator it = lineBySlope.find(key);
	if (it == lineBySlope.end()){
		lineBySlope[key] = v;
		lineBySlope[key].push_back(line);
	}
	else{
		lineBySlope[key].push_back(line);
	}
	
}

Line findBestLine(Point points[],int length){
	Line bestLine;
	int bestCount = 0;
	hash_map<double, vector<Line>> linesBySlope;
	for (int i = 0; i < length; ++i){
		for (int j = i + 1; j < length; ++j){
			Line line(points[i], points[j]);
			insertLine(linesBySlope, line);
			int count = countEquivalentLines(linesBySlope, line);
			if (count > bestCount){
				bestLine = line;
				bestCount = count;
			}
		}
	}
	return bestLine;
}

int main(){
	Point p[6] ;
	p[0] = Point(1, 1);
	p[1] = Point(2, 3);
	p[2] = Point(3, 3);
	p[3] = Point(4, 5);
	p[4] = Point(6, 10);
	p[5] = Point(7, 7);
	Line l = findBestLine(p,sizeof(p)/sizeof(Point));

	cout << std::fixed << l.intercept << " " << l.slope << endl;


	cin.get();
	return 0;
}



结果显示正确



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值