P5143 攀爬者(结构体+sort排序)

P5143 攀爬者

sort排序

  • 对于数组而言
    sort(数组+begin,数组+stop)(左闭右开)
    例:
    sort(a+1,a+n+1)=sort(a[1]~a[n])
    对于结构体
    在数组基础上多一个cmp
    运用:sort(数组+begin,数组+stop,cmp)
  • cmp本身需要定义一个函数来表示比较。
bool cmp(结构体 b, 结构体 c) {
	return b.z > c.z;
}

前大于后表示排序从大到小
前小于后表示排序从小到大

#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
using namespace std;

struct mountain {
	int x, y, z;
} a[50001];

bool cmp(mountain b, mountain c) {
	return b.z > c.z;
}
double ans;

int main() {
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i].x >> a[i].y >> a[i].z;
	}
	sort(a + 1, a + n, cmp);
	for (int i = 1; i <= n - 1; 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));
	}
	printf("%.3f", ans);
	return 0;
}
posted @ 2023-11-23 22:13  拍手称快  阅读(71)  评论(0)    收藏  举报