#include<iostream>
#include<math.h>
#include <graphics.h>
#include <conio.h>
using namespace std;
#define MAX 1.79769e+308
class ClosestPoints{
private:
 int n;
 double P[100][2];
 int x1,x2;
 int y1,y2;
public:
 void set_points();
 void do_points();
 void print();
};
void ClosestPoints::set_points()
{
 cin>>n;
 for(int i=0;i<n;i++)
  {
   cin>>P[i][0];
   cin>>P[i][1];
 }
}
void ClosestPoints::do_points()
{
 double mind = MAX;
 double dis;
 x1 = 0,y1 = 0;
 x2 = 0,y2 = 0;
 for(int i=0;i<n-1;i++)
  for(int j=i+1;j<n;j++)
  {
   dis = (P[j][0]-P[i][0])*(P[j][0]-P[i][0])+(P[j][1]-P[i][1])*(P[j][1]-P[i][1]);
   if(dis<mind)
   {
    mind = dis;
    x1 = P[i][0];
    y1 = P[i][1];
    x2 = P[j][0];
    y2 = P[j][1];
   }
  }
 cout<<sqrt(mind)<<" "<<x1<<" "<<y1<<" "<<x2<<" "<<y2<<endl;
}
void ClosestPoints::print()
{
 initgraph(640, 480);
 setorigin(0,0);
 for(int i=0;i<n;i++)
 {
  fillcircle(P[i][0]*50,P[i][1]*50,2);
  Sleep(100);
 }
 for(int i=0;i<n;i++)
  for(int j=i+1;j<n;j++)
   {
    line(P[i][0]*50,P[i][1]*50,P[j][0]*50,P[j][1]*50);
    Sleep(100);
  }
 setlinecolor(RED);
 line(x1*50,y1*50,x2*50,y2*50);
 _getch();
    closegraph();
}
int main()
{
 ClosestPoints C1;
 C1.set_points();
 C1.do_points();
 C1.print();
 return 0;
}

采用蛮力法求出所有点之间的距离,然后进行比较找出第一个最近对
画图输出

c++蛮力法解决最近对问题(可视化)

相关文章: