TH2-01.CPP: Giải bài toán người bán hàng bằng thuật toán quay lui (hoặc nhánh cận)
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 100;
const int INF = 1e9;
int n, cost[MAX][MAX], path[MAX], visited[MAX], ans = INF;
// Hàm kiểm tra thành phố i đã được đi qua hay chưa
bool isVisited(int i) {
return visited[i] != 0;
}
// Hàm tính tổng chi phí của hành trình hiện tại
int calc_cost(int k) {
int sum = 0;
for (int i = 1; i < k; i++) {
sum += cost[path[i - 1]][path[i]];
}
return sum;
}
// Hàm quay lui tìm hành trình
void TSP(int k) {
for (int i = 1; i <= n; i++) {
if (!isVisited(i)) {
path[k] = i;
visited[i] = 1;
if (k == n) {
int current_cost = calc_cost(n + 1) + cost[path[n]][0];
if (current_cost < ans) {
ans = current_cost;
}
} else {
if (calc_cost(k) < ans) {
TSP(k + 1);
}
}
visited[i] = 0;
}
}
}
int main() {
cout << "Nhap so thanh pho: ";
cin >> n;
cout << "Nhap ma tran chi phi: \n";
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
cin >> cost[i][j];
}
}
visited[0] = 1;
path[0] = 0;
TSP(1);
cout << "Chi phi thap nhat: " << ans;
return 0;
}
TH2-02.CPP: Giải bài toán người bán hàng bằng thuật toán quy hoạch động
#include <iostream>
#include <vector>
#include <algorithm>
#include <bitset>
using namespace std;
const int MAX = 20;
const int INF = 1e9;
int n, cost[MAX][MAX], dp[(1<<MAX) + 5][MAX];
int TSP_DP(int mask, int pos) {
if (mask == (1 << n) - 1) {
return cost[pos][0];
}
if (dp[mask][pos] != -1) {
return dp[mask][pos];
}
int ans = INF;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) == 0) {
int new_mask = mask | (1 << i);
ans = min(ans, cost[pos][i] + TSP_DP(new_mask, i));
}
}
return dp[mask][pos] = ans;
}
int main() {
cout << "Nhap so thanh pho: ";
cin >> n;
cout << "Nhap ma tran chi phi: \n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> cost[i][j];
}
}
for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
dp[i][j] = -1;
}
}
cout << "Chi phi thap nhat: " << TSP_DP(1, 0);
return 0;
}