蛮力法解决最近对问题

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/84591167

跑个O(n^2),没啥可说的,直接上代码和数据。

C++代码

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;

const int maxn = 10005;

typedef struct Point
{
    double x;
    double y;
} point;

point p[maxn];

double getlen(point p1, point p2)
{
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

int main()
{
    int n;
    while (cin >> n && n)
    {
        for (int i = 0; i < n; i++) cin >> p[i].x >> p[i].y;

        double min_len = INF;
        double x1, y1, x2, y2;

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

                double len = getlen(p[i], p[j]);

                if (len < min_len)
                {
                    min_len = len;
                    x1 = p[i].x;
                    y1 = p[i].y;
                    x2 = p[j].x;
                    y2 = p[j].y;
                }
            }
        }

        printf("%.3lf (%.3lf, %.3lf) (%.3lf, %.3lf)\n", min_len, x1, y1, x2, y2);

    }

    return 0;
}

测试数据

/*
input1
6
1 3
2 1
4 1
4 3
3 4
6 2

output1
1.414 (4.000, 3.000) (3.000, 4.000)

input2
14
30 30
50 60
60 20
70 45
86 39
112 60
200 113
250 50
300 200
130 240
76 150
47 76
36 40
33 35

ouput2
5.831 (30.000, 30.000) (33.000, 35.000)
*/

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/84591167