Max Points on a Line

来源:互联网 发布:钢管承载力计算软件 编辑:程序博客网 时间:2024/04/30 05:38
/* * Solution.cpp * *  Created on: 2014年3月26日 *      Author: William *//** * Definition for a point. * struct Point { *     int x; *     int y; *     Point() : x(0), y(0) {} *     Point(int a, int b) : x(a), y(b) {} * }; */#include <iostream>#include <string>#include <vector>#include <map>using namespace std;int gcd(int, int);string to_string(int);struct Point{int x;int y;Point() :x(0), y(0){}Point(int a, int b) :x(a), y(b){}};class Solution{public:int maxPoints(vector<Point> &points){int ans = 0;for (int i = 0; i < points.size(); i++) {map<string, int> mp;int tempans = 0, same = 0;for (int j = i+1; j < points.size(); j++) {int x = points[j].x - points[i].x;int y = points[j].y - points[i].y;int g = gcd(x,y);// Get the greatest common divisor.if (g == 0) same++;// If g=0, x=y=0. Which means i and j are the same point.// Use 'same' as a special counter for the same point situation.else {x /= g, y /= g; // Use greatest common divisor to get the slope into the simplest fraction.if (x < 0) x = -x, y = -y;// Make x positive for consistency.string slope = to_string(x) + " " + to_string(y);if (!mp.count(slope)) mp[slope] = 1;else mp[slope]++;tempans = max(tempans, mp[slope]);}}ans = max(ans, 1+tempans+same);}return ans;}};int gcd(int a, int b){return a ? gcd(b % a, a) : b;}// 关于最大公约数的求法,利用欧几里得辗转相除法// 辗转相除法,也就是将大数除以小数,将所得约数与小数继续递归使用辗转相除法,直到一个数为0,则另一数为最小公倍数// 以上这个函数的巧妙之处在于:1.只考虑a为小数,b为大数的情况,而如果两者情况想法,则b%a=b,gcd(b%a,a)等同于gcd(b,a),自动起到了交换的作用;//2。由于a为始终视作小数,因此只需判断a是否是0,无需使用if分别判断a和b,使用选择运算符即可。string to_string(int a){char *buf = new char[10];sprintf(buf, "%d", a);string str(buf);delete buf;return str;}//int main()//{//vector<Point> ps;//ps.insert(ps.end(),Point(0,0));//ps.insert(ps.end(),Point(1,1));//ps.insert(ps.end(),Point(1,1));//Solution pro;//int result = pro.maxPoints(ps);//cout << result << endl;//return 0;//}

0 0