您的位置:首页 > 其它

给定一个平面内的点的集合,求共线最多点的个数。要求减少重复运算,并给出测试案例。

2017-01-09 10:23 423 查看
思路:对于集合中的任意两点,循环遍历剩下的点,判断是否与其共线,记录下共线点的个数,找出其中一个最大的共线点的个数

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;

struct Point {
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};

class pointSolution {
public:
bool isCollineation(Point& p1, Point& p2, Point& p3)//判断三点是否共线
{
int x1 = p2.x - p1.x;
int y1 = p2.y - p1.y;
int x2 = p3.x - p1.x;
int y2 = p3.y - p1.y;
if (x1 * y2 == x2 * y1)  //共线的定义
return true;
return false;
}
int maxPoints(vector<Point> &points)
{

if (points.size() <= 2)
{
return points.size();
}
int maxLine = 2;

bool flag = false;//检测是否所有点都重合
for (size_t i = 0; i < points.size(); ++i)
{
int repNum = 0;//记录重复点的个数
for (size_t j = i + 1; j < points.size(); ++j)
{
if (points[i].x == points[j].x && points[i].y == points[j].y)
{
repNum++;
continue;
}
flag = true;
int count = 2 + repNum;
for (size_t k = j + 1; k < points.size(); ++k)
if (isCollineation(points[i], points[j], points[k]))
count++;
if (count > maxLine)
maxLine = count;
}
}

if (!flag)
{
maxLine = points.size();
}
return maxLine;
}
};

int main()
{
srand((unsigned int) time(NULL));
int x = 0, y = 0;
vector<Point> points;
for(int i = 0; i < 50; i++)
{
points.push_back(Point(rand() % 100, rand() % 100));
}
pointSolution ps;
cout <<"共线最多点的个数是:"<< ps.maxPoints(points) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: