旅行商问题用回溯法以及排列空间树解决,请给我具体C++实现代码
时间: 2024-02-24 08:59:28 浏览: 59
好的,以下是旅行商问题的回溯法和排列空间树的C++实现代码:
回溯法:
```
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 20;
int n, ans = INF;
int map[MAXN][MAXN];
bool vis[MAXN];
void dfs(int cur, int cost, int cnt) {
if (cnt == n && map[cur][0] != INF) {
ans = min(ans, cost + map[cur][0]);
return;
}
if (cost >= ans) return;
for (int i = 1; i <= n; i++) {
if (!vis[i] && map[cur][i] != INF) {
vis[i] = true;
dfs(i, cost + map[cur][i], cnt + 1);
vis[i] = false;
}
}
}
int main() {
memset(vis, false, sizeof(vis));
memset(map, INF, sizeof(map));
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
}
}
vis[0] = true;
dfs(0, 0, 0);
cout << ans << endl;
return 0;
}
```
排列空间树:
```
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 20;
int n, ans = INF;
int map[MAXN][MAXN];
bool vis[MAXN];
void dfs(int cur, int cost, int cnt) {
if (cnt == n && map[cur][0] != INF) {
ans = min(ans, cost + map[cur][0]);
return;
}
if (cost >= ans) return;
for (int i = 1; i <= n; i++) {
if (!vis[i] && map[cur][i] != INF) {
vis[i] = true;
dfs(i, cost + map[cur][i], cnt + 1);
vis[i] = false;
}
}
}
int main() {
memset(vis, false, sizeof(vis));
memset(map, INF, sizeof(map));
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
}
}
vis[0] = true;
dfs(0, 0, 0);
cout << ans << endl;
return 0;
}
```
阅读全文