From fe89149911899fde0baf56da7a312d06dafcdee2 Mon Sep 17 00:00:00 2001 From: Ishan Pandhare <91841626+Ishanned@users.noreply.github.com> Date: Sat, 7 Oct 2023 13:54:50 +0530 Subject: [PATCH] Create travelling-salesman-dp added dp implementation of travelling salesman problem --- c++/travelling-salesman-dp | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 c++/travelling-salesman-dp diff --git a/c++/travelling-salesman-dp b/c++/travelling-salesman-dp new file mode 100644 index 0000000..8068fae --- /dev/null +++ b/c++/travelling-salesman-dp @@ -0,0 +1,42 @@ +#include + +using namespace std; +const int n = 4; +const int MAX = 1000000; + +int dist[n + 1][n + 1] = { + { 0, 0, 0, 0, 0 }, { 0, 0, 10, 15, 20 }, + { 0, 10, 0, 25, 25 }, { 0, 15, 25, 0, 30 }, + { 0, 20, 25, 30, 0 }, +}; +int memo[n + 1][1 << (n + 1)]; + +int fun(int i, int mask) +{ + if (mask == ((1 << i) | 3)) + return dist[1][i]; + if (memo[i][mask] != 0) + return memo[i][mask]; + + int res = MAX; + + for (int j = 1; j <= n; j++) + if ((mask & (1 << j)) && j != i && j != 1) + res = std::min(res, fun(j, mask & (~(1 << i))) + + dist[j][i]); + return memo[i][mask] = res; +} + +int main() +{ + int ans = MAX; + for (int i = 1; i <= n; i++) + + ans = std::min(ans, fun(i, (1 << (n + 1)) - 1) + + dist[i][1]); + + printf("The cost of most efficient tour = %d", ans); + + return 0; +} +