標籤:style blog color 使用 io for div line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:對於兩個點(x1,y1)和(x2,y2),其所確定的直線方程為:(x1-x2)*y + (y2-y1)*x + x2*y1-x1*y2 = 0,即:a*y + b*x + c = 0。
使用類似廣度優先遍曆的思想,Q[i]儲存了第i+1個點與前i個點中的每一個點所確定的直線、以及前i+1個點中經過該直線的點的數目,Q[i][0]表示第i+1個點已經出現的次數。
依次處理輸入序列的每一個元素,對於當前元素i,依次訪問每一個Q[k] (k = i-1, i-2, ..., 0),遍曆Q[k]找到經過點i和點k所確定的直線的最大的點的數目,儲存在Q[i]中。
從後往前訪問Q[k]的過程中,在第一次遇見點i和點k重合時,更新Q[i][0]的次數值。
1 class Line 2 { 3 public: 4 Line(): a(0), b(0), c(0), cnt(1) {} 5 ~Line(){} 6 public: 7 int a, b, c; 8 int cnt; 9 };10 11 class Solution {12 public:13 int maxPoints( vector<Point> &points ) {14 if( points.size() <= 2 ) { return points.size(); }15 vector<Line>* Q = new vector<Line>[points.size()];16 Q[0].resize(1);17 int max_num = 2;18 Line optimal;19 for( int i = 1; i < points.size(); ++i ) {20 Q[i].resize(1);21 for( int j = i-1; j >= 0; --j ) {22 optimal.a = points[i].x-points[j].x;23 optimal.b = points[j].y-points[i].y;24 optimal.c = points[j].x*points[i].y-points[i].x*points[j].y;25 if( points[i].x == points[j].x && points[i].y == points[j].y ) {26 if( Q[i][0].cnt == 1 ) { Q[i][0].cnt = Q[j][0].cnt+1; }27 else { continue; }28 optimal.cnt = Q[i][0].cnt;29 for( size_t ID = 1; ID != Q[j].size(); ++ID ) {30 Line& aLine = Q[j][ID];31 if( aLine.a*points[i].y + aLine.b*points[i].x + aLine.c == 0 ) {32 if( optimal.cnt <= aLine.cnt+1 ) { optimal = aLine; ++optimal.cnt; }33 }34 }35 } else {36 optimal.cnt = 2;37 for( size_t ID = 0; ID != Q[j].size(); ++ID ) {38 Line& aLine = Q[j][ID];39 if( aLine.a*points[i].y + aLine.b*points[i].x + aLine.c == 0 ) {40 if( optimal.cnt < aLine.cnt+1 ) { optimal.cnt = aLine.cnt+1; }41 }42 }43 }44 if( max_num < optimal.cnt ) { max_num = optimal.cnt; }45 Q[i].push_back( optimal );46 }47 }48 delete[] Q;49 return max_num;50 }51 };