-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathtsp_using_BitMaskDP.cpp
More file actions
44 lines (35 loc) · 1.13 KB
/
tsp_using_BitMaskDP.cpp
File metadata and controls
44 lines (35 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n; // number of cities
vector<vector<int>> dist; // distance matrix
vector<vector<int>> dp; // dp[mask][i] = min cost to visit all cities in 'mask' ending at i
int tsp(int mask, int pos) {
if (mask == (1 << n) - 1)
return dist[pos][0]; // return to start city
if (dp[mask][pos] != -1)
return dp[mask][pos];
int ans = INF;
for (int city = 0; city < n; city++) {
if ((mask & (1 << city)) == 0) {
int newCost = dist[pos][city] + tsp(mask | (1 << city), city);
ans = min(ans, newCost);
}
}
return dp[mask][pos] = ans;
}
int main() {
cout << "Enter number of cities: ";
cin >> n;
dist.assign(n, vector<int>(n));
cout << "Enter the distance matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> dist[i][j];
}
}
dp.assign(1 << n, vector<int>(n, -1));
int result = tsp(1, 0); // start from city 0 with mask = 000...001
cout << "\nMinimum cost to visit all cities and return: " << result << endl;
return 0;
}