题目描述

样例

源代码
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
class Position
{
public:
int distance;
int num;
};
bool compare(Position a, Position b)
{
if (a.distance != b.distance)
return a.distance < b.distance;
else if (a.num != b.num)
return a.num < b.num;
}
int main()
{
int n, x, y;
int a, b;
Position d[201];
cin >> n >> x >> y;
for (int i = 0; i < n; i++)
{
cin >> a >> b;
int distance = pow((a - x), 2) + pow((b - y), 2);
d[i] = { distance,i + 1 };
}
sort(d, d + n, compare);
for (int i = 0; i < 3; i++)
cout << d[i].num << endl;
return 0;
}
关于这题
这里距离不用开方 直接记录平方就好 这里用的pow
这种要比较距离的同时 还要记录编号 最好用结构体 或者类
这里用的类 当然用pair也行
sort 是一个排序函数 排序方式 是自定义的compare

该博客介绍了一个C++程序,用于计算并排序二维平面上点与特定点的距离。程序利用结构体存储每个点的距离和编号,并通过自定义的比较函数进行排序。排序后输出最近的三个点的编号。此代码示例涉及到了排序算法和距离计算的应用。
695

被折叠的 条评论
为什么被折叠?



