给定一个平面内的点的集合,求共线最多点的个数。要求减少重复运算,并给出测试案例。
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; }
相关文章推荐
- Lua学习---函数定义
- 微信小程序入门篇
- C语言中实现函数返回字符串
- 几种Python执行时间的计算方法
- Openstack-I版计算节点:Nova/Neutron/Ceilometer服务不断重启
- 架构师知识体系(1)--WEB架构师成长之路
- vue渲染从后台获取的json数据
- Qt5基本教程
- corosync+pacemaker使用pcs构建高可用集群
- Python目录
- Linux打补丁常用命令
- 三维转二维数组
- Linux打补丁常用命令
- MEMCACHE与REDIS
- Spring IOC的理解
- 宏内核与微内核【转】
- easyui datebox 时间格式化(Mon Jan 02 00:00:00 cst 2017)
- 《iOS 7 Human Interface Guidelines中文版》读书笔记(2)
- 谷歌浏览器启动页被篡改为hao.7654.com的解决办法
- 设置文件上传限制(解除限制)