P5143 题解

· · 题解

传送门:P5143 攀爬者

更佳的阅读体验:洛谷 P5143 题解

简要题意:给定 n 个三维点,每个点的 z 坐标唯一,要求按照 z 坐标升序访问所有点,并计算相邻两点间欧几里得距离的总和。

我们可以创建一个坐标结构体,用于存放每个点的 x, y, z 坐标。然后按 z 坐标排序,把相邻两点的欧几里得距离全部加起来即可。

对于排序规则,下文代码中使用了重载 < 运算符,它等价于编写一个自定义排序函数。编写自定义排序函数的做法将以注释的形式给出。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;

const int N = 5e4 + 10;
int n;
struct pos {
    double x, y, z;
    bool operator<(const pos x) const {
        return z < x.z;
    }
} a[N];
double ans;

/* bool cmp(pos a, pos b) {
    return a.z < b.z;
} */

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i].x >> a[i].y >> a[i].z;
    sort(a + 1, a + n + 1);
    // sort(a + 1, a + n + 1, cmp);
    for (int i = 1; i < n; ++i)
        ans += sqrt((a[i].x - a[i + 1].x) * (a[i].x - a[i + 1].x) + (a[i].y - a[i + 1].y) * (a[i].y - a[i + 1].y) + (a[i].z - a[i + 1].z) * (a[i].z - a[i + 1].z));
    cout << fixed << setprecision(3) << ans << '\n';
    return 0;
}