n个点的曼哈顿距离和c++
时间: 2024-06-17 12:07:52 浏览: 9
曼哈顿距离也称为城市街区距离,是指在笛卡尔坐标系上,两个点的横坐标差的绝对值加上纵坐标差的绝对值。即对于两个点 $(x_1,y_1)$ 和 $(x_2,y_2)$,它们之间的曼哈顿距离为 $|x_1-x_2|+|y_1-y_2|$。
如果你想在 C++ 中计算 n 个点的曼哈顿距离,可以先定义一个结构体表示每个点的坐标,然后用两重循环计算每两个点之间的曼哈顿距离。
下面是一个简单的代码示例:
```c++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct Point {
int x, y;
};
int manhattan_distance(Point a, Point b) {
return abs(a.x - b.x) + abs(a.y - b.y);
}
int main() {
int n;
cin >> n;
vector<Point> points(n);
for (int i = 0; i < n; i++) {
cin >> points[i].x >> points[i].y;
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
cout << "The Manhattan distance between point " << i << " and point " << j << " is: "
<< manhattan_distance(points[i], points[j]) << endl;
}
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)