/* VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I." VIM: let b:wcppflags="/O2 /EHsc /DWIN32" */ #include "stdafx.h" #include #include #include #include #include #include #include #include #include #include #include #include /* https://leetcode.com/problems/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. */ struct Point { int x; int y; Point() : x(0), y(0) {} Point(int a, int b) : x(a), y(b) {} }; struct pairhash { std::size_t operator() (const Point& p) const { return std::hash()(p.x) ^ std::hash()(p.y); } }; bool operator == (const Point& p1, const Point& p2) { return p1.x == p2.x && p1.y == p2.y; } Point ratio(int x, int y) { if (x == 0) { return Point(0, 1); } else if (y == 0) { return Point(1, 0); } else if ( x < 0 ) { x = -x; y = -y; } int a = std::max(abs(x), abs(y)); int b = std::min(abs(x), abs(y)); for (int c; (c = a % b); a = b, b = c); return Point(x / b, y / b); } int solve(const std::vector& v) { std::unordered_map vv; for (const auto& p : v) { vv[p]++; } if (vv.empty()) { return 0; } else if (vv.size()==1) { return vv.begin()->second; } int max_points = 1; for (auto i = vv.begin(); i != vv.end(); i++) { std::unordered_map s; for (auto j = std::next(i); j != vv.end(); j++) { const auto line = ratio(i->first.x - j->first.x, i->first.y - j->first.y); s[line] += j->second; max_points = std::max(max_points, s[line] + i->second); } } return max_points; } int main() { try { auto begin = std::chrono::high_resolution_clock::now(); std::cout << solve({ { 1,1 },{ 2,2 },{ 3,3 } }) << std::endl; std::cout << solve({ { 1,1 },{ 3,2 },{ 5,3 },{ 4,1 },{ 2,3 },{ 1,4 } }) << std::endl; std::cout << solve({ { 2, 3 },{ 3, 3 },{ -5, 3 } }) << std::endl; std::cout << solve({ { 2, 2 },{ 3, 3 },{ 2, 2 },{ 3, 3 } }) << std::endl; std::cout << solve({ { 2, 2 },{ 2, 3 },{ 3, 2 },{ 3, 3 } }) << std::endl; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration seconds = end - begin; std::cout << "Time: " << seconds.count() << std::endl; return 0; } catch (const std::exception& e) { std::cerr << std::endl << "std::exception(\"" << e.what() << "\")." << std::endl; return 2; } catch (...) { std::cerr << std::endl << "unknown exception." << std::endl; return 1; } }