c++改写import sysINF = sys.maxsize # 设置正无穷n, m = map(int, input().split())cost = [[INF] * n for _ in range(n)]for i in range(m): a, b, c = map(int, input().split()) cost[a][b] = c# DP求解dp = [[INF] * n for _ in range(1 << n)]path = [[-1] * n for _ in
时间: 2023-11-28 10:49:41 浏览: 58
from sys import maxsize.py
C++中没有类似于Python的`input()`函数,需要使用`cin`来读取输入。另外,`map()`在C++中也没有直接的对应,可以使用`istringstream`来将输入的字符串转换为数值类型。以下是将代码从Python改写为C++的示例:
```cpp
#include <iostream>
#include <sstream>
#include <vector>
#include <cstring>
using namespace std;
const int INF = 1e9;
int n, m;
vector<vector<int>> cost;
vector<vector<int>> dp;
vector<vector<int>> path;
int main() {
cin >> n >> m;
cost.resize(n, vector<int>(n, INF));
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
cost[a][b] = c;
}
dp.resize(1 << n, vector<int>(n, INF));
path.resize(1 << n, vector<int>(n, -1));
for (int i = 0; i < n; i++) {
dp[1 << i][i] = 0;
}
for (int S = 0; S < (1 << n); S++) {
for (int v = 0; v < n; v++) {
for (int u = 0; u < n; u++) {
if (!(S & (1 << u))) continue;
if (dp[S][v] > dp[S - (1 << u)][u] + cost[u][v]) {
dp[S][v] = dp[S - (1 << u)][u] + cost[u][v];
path[S][v] = u;
}
}
}
}
// 输出最短路径
int S = (1 << n) - 1, v = 0;
vector<int> ans;
while (S) {
int u = path[S][v];
ans.push_back(v);
v = u;
S -= (1 << u);
}
ans.push_back(0);
// 输出结果
cout << "最短路径长度:" << dp[(1 << n) - 1][0] << endl;
cout << "最短路径:";
for (int i = ans.size() - 1; i >= 0; i--) {
cout << ans[i] << " ";
}
cout << endl;
return 0;
}
```
阅读全文