请使用c++编写上面那道题
时间: 2024-04-16 10:24:05 浏览: 47
C/C++面试题:编写类String的构造、析构和赋值函数
以下是使用 C++ 编写的代码来解决上述问题:
```cpp
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// 计算两点之间的距离
int distance(int x1, int y1, int x2, int y2) {
return pow(x1 - x2, 2) + pow(y1 - y2, 2);
}
int min_cost(int x1, int y1, int x2, int y2, vector<pair<int, int>>& routers) {
int n = routers.size();
vector<vector<int>> dp(n+1, vector<int>(n+1, INT_MAX));
dp[0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= i; j++) {
if (j < i) {
dp[i][j] = dp[i-1][j] + distance(x1, y1, routers[i-1].first, routers[i-1].second);
}
if (i > 0 && j > 0) {
dp[i][j] = min(dp[i][j], dp[i][j-1] + distance(x2, y2, routers[j-1].first, routers[j-1].second));
}
}
}
return dp[n][n];
}
int main() {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
int n;
cin >> n;
vector<pair<int, int>> routers;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
routers.push_back(make_pair(x, y));
}
int result = min_cost(x1, y1, x2, y2, routers);
cout << result << endl;
return 0;
}
```
请注意,此代码假设输入的坐标和路由器数量的范围在有效范围内。如果你对代码有任何疑问,请随时询问。
阅读全文