兩個點集各取一個點,使距離最小


題目連接  https://www.acwing.com/problem/content/121/

 

 

 

 

輸入樣例:

2
4
0 0
0 1
1 0
1 1
2 2
2 3
3 2
3 3
4
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0

輸出樣例:

1.414 0.000

https://www.cnblogs.com/-citywall123/p/13174180.html
參考上篇博客,平面最小點集的變形,把不同集合點標記一下,只有不同集合的兩個點才可以求距離,否則返回距離為無窮
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const double inf = 1e20;
const int maxn = 100005;

struct Point {
    double x, y;
    int Type;
}point[maxn];

int n, mpt[maxn];


//以x為基准排序
bool cmpxy(const Point& a, const Point& b) {
    if (a.x != b.x)
        return a.x < b.x;
    return a.y < b.y;
}

bool cmpy(const int& a, const int& b) {
    return point[a].y < point[b].y;
}

double min(double a, double b) {
    return a < b ? a : b;
}
//求兩點距離
double dis(int i, int j) {
    //只有不同集合的點可以求距離
    if (point[i].Type == point[j].Type)return inf;

    return sqrt((point[i].x - point[j].x)*(point[i].x - point[j].x) + (point[i].y - point[j].y)*(point[i].y - point[j].y));
}
//將平面二分為左右兩個點集,分別找平面左右兩邊中最短的距離d
//然后再把平面區間在[left,right]范圍內的點中,把p.x到中點mid距離小於d的點標記
//被標記的點按x坐標再次排序
//兩個for遍歷這個點集,更新最小距離d
double Closest_Pair(int left, int right) {
    double d = inf;
    if (left == right)
        return d;
    if (left + 1 == right)
        return dis(left, right);
    int mid = (left + right) >> 1;
    double d1 = Closest_Pair(left, mid);
    double d2 = Closest_Pair(mid + 1, right);
    d = min(d1, d2);
    int i, j, k = 0;
    //分離出寬度為d的區間
    for (i = left; i <= right; i++) {
        if (fabs(point[mid].x - point[i].x) <= d)
            mpt[k++] = i;
    }
    sort(mpt, mpt + k, cmpy);
    //線性掃描
    for (i = 0; i < k; i++) {
        for (j = i + 1; j < k && point[mpt[j]].y - point[mpt[i]].y < d; j++) {
            double d3 = dis(mpt[i], mpt[j]);
            if (d > d3)    d = d3;
        }
    }
    return d;
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        for (int i = 0; i < n; i++) {
            scanf("%lf %lf", &point[i].x, &point[i].y);
            point[i].Type = 0;
        }
        for (int i = n; i < n * 2; i++) {
            scanf("%lf %lf", &point[i].x, &point[i].y);
            point[i].Type = 1;
        }
        n = n * 2;
        sort(point, point + n, cmpxy);
        printf("%.3lf\n", Closest_Pair(0, n - 1) );
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM