Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

#include #include #include using namespace std; const int N = 1e5 + 5; struct Point { double x, y; bool operator = r) return 1e9;

#include

#include

#include

using namespace std;

const int N = 1e5 + 5;

struct Point {

double x, y;

bool operator<(const Point &p) const {

return x < p.x || (x == p.x && y < p.y);

}

} points[N];

double dist(Point a, Point b) {

double dx = a.x - b.x, dy = a.y - b.y;

return sqrt(dx * dx + dy * dy);

}

double closestPair(int l, int r) {

if (l >= r) return 1e9;

if (l + 1 == r) return dist(points[l], points[r]);

int mid = l + r >> 1;

double d = min(closestPair(l, mid), closestPair(mid + 1, r));

int i = l, j = mid + 1, k = 0;

Point strip[r - l + 1];

while (i <= mid && j <= r) {

if (points[i] < points[j]) strip[k++] = points[i++];

else strip[k++] = points[j++];

}

while (i <= mid) strip[k++] = points[i++];

while (j <= r) strip[k++] = points[j++];

for (int i = 0; i < k; i++) points[l + i] = strip[i];

i = 0;

for (int j = l; j <= r; j++) {

if (abs(points[j].x - points[mid].x) >= d) continue;

while (i < k - 1 && points[l + i + 1].y < points[j].y) i++;

for (int t = i; t < k && points[l + t].y - points[j].y < d; t++) {

d = min(d, dist(points[l + t], points[j]));

}

}

return d;

}

int main() {

int n;

cin >> n;

for (int i = 0; i < n; i++) {

cin >> points[i].x >> points[i].y;

}

sort(points, points + n);

cout << closestPair(0, n - 1) << endl;

return 0;

}

Please comment part by part of a code.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Inductive Databases And Constraint Based Data Mining

Authors: Saso Dzeroski ,Bart Goethals ,Pance Panov

2010th Edition

1489982175, 978-1489982179

Students also viewed these Databases questions

Question

Discuss consumer-driven health plans.

Answered: 1 week ago