找出平面上距离最近的两个点

时间:2021-10-13 14:38:43
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
 
 using namespace std;
 struct point
 {
 	point(double x, double y)
 	{
 		x_ = x;
 		y_ = y;
 	}
 	double x_;
 	double y_;
 };


int main(int argc, char* argv[])
{
	int n;
	scanf("%d", &n);

	vector<point> pvec;
	for(int i = 0; i < n; ++i)
	{
		double x;
		double y;
		scanf("%lf%lf", &x, &y);
		point p(x, y);
		pvec.push_back(p);
	}

	int mlen = 0;
	int start = 0;
	int end = 0;
	for(int i = 0; i < pvec.size(); ++i)
	{

		for(int j = i + 1; j < pvec.size(); ++j)
		{

			double d2 = pow(pvec[i].x_ - pvec[j].x_, 2) + pow(pvec[i].y_ - pvec[j].y_, 2);

			if(mlen == 0)
			{
				mlen = d2;
			}else if(mlen > d2)
			{
				mlen = d2;
				start = i;
				end = j;
			}else
			{}

		}

	}

	if(start < end)
	{
		printf("closest point: %d,%d\n", start, end);
	}else
	{
		printf("closest point: %d,%d\n", end, start);
	}

	return 0;
}