{{{#include #include #include #include using namespace std; typedef pair Point2D; typedef pair ClosePoint; int getDistance(Point2D from, Point2D to) { return (from.first - to.first ) * (from.first - to.first ) + (from.second -to.second) * (from.second - to.second); } class Solution { public: Solution(); ~Solution(); ClosePoint find(int start_x, int end_x); void solve(const char *input, const char *output); private: fstream source_fp; fstream target_fp; vector points; }; int main() { Solution solve; solve.solve("input3_2.txt", "output_2.txt"); return 0; } Solution::Solution() { } Solution::~Solution() { source_fp.close(); target_fp.close(); } ClosePoint Solution::find(int start_x, int end_x) { ClosePoint result; ClosePoint CP1, CP2; int i = 0, j = 0; int left = 0, right = 0; int tempLength = 0; int length = 10000; int distance_cp1 = 0, distance_cp2 = 0; // cout << start_x << " " << end_x << endl; if ( end_x - start_x < 50 ) { for ( i = start_x; i < end_x-1; i++ ) { for ( j = i+1 ; j < end_x; j++ ) { tempLength = getDistance(points[i], points[j]); if ( tempLength < length ) { length = tempLength; result.first = points[i]; result.second = points[j]; } } } } else { CP1 = find(start_x, start_x + (end_x-start_x)/2); CP2 = find(start_x + (end_x-start_x)/2, end_x); distance_cp1 = getDistance(CP1.first, CP1.second); distance_cp2 = getDistance(CP2.first, CP2.second); if ( distance_cp1 < distance_cp2 ) { result = CP1; length = distance_cp1; } else { result = CP2; length = distance_cp2; } for ( left = start_x; points[left].first < (points[start_x+(end_x-start_x)/2].first - length - 1) ; left++ ); for ( right = end_x-1; points[right].first > (points[start_x+(end_x-start_x)/2].first + length + 1) ; right-- ); for ( i = left; i < right-1; i++ ) { for ( j = i+1 ; j < right; j++ ) { tempLength = getDistance(points[i], points[j]); if ( tempLength < length ) { length = tempLength; result.first = points[i]; result.second = points[j]; } } } } return result; } void Solution::solve(const char *input,const char *output) { int nCount = 0; int i = 0, j = 0; Point2D tempPoint; Point2D start; Point2D end; ClosePoint result; int length = 10000; int tempLength = 0; source_fp.open(input,ios::in); target_fp.open(output,ios::out); source_fp >> nCount; for ( i = 0; i < nCount; i++ ) { source_fp >> tempPoint.first >> tempPoint.second; points.push_back(tempPoint); } clock_t start_time; clock_t end_time; start_time = clock(); result = find(0, nCount); end_time = clock(); start = result.first; end = result.second; target_fp << (double)(end_time - start_time)/CLOCKS_PER_SEC << endl; target_fp << start.first << " " << start.second << endl; target_fp << end.first << " " << end.second; }}}}