1. 程式人生 > >蠻力法解決最近對問題

蠻力法解決最近對問題

跑個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)
*/