0

According to this recursion formula for dynamic programming (Held–Karp algorithm), the minimum cost can be found. I entered this code in C ++ and this was achieved (neighbor vector is the same set and v is cost matrix):

recursion formula :

C(i,S) = min { d(i,j) + C(j,S-{j}) }

my code :

#include <iostream>
#include <vector>
#define INF 99999
using namespace std;
vector<vector<int>> v{ { 0, 4, 1, 3 },{ 4, 0, 2, 1 },{ 1, 2, 0, 5 },{ 3, 1, 5, 0 } };
vector<int> erase(vector<int> v, int j)
{
    v.erase(v.begin() + j);
    vector<int> vv = v;
    return vv;
}
int TSP(vector<int> neighbor, int index)
{
    if (neighbor.size() == 0)
        return v[index][0];
    int min = INF;
    for (int j = 0; j < neighbor.size(); j++)
    {
        int cost = v[index][neighbor[j]] + TSP(erase(neighbor, j), neighbor[j]);
        if (cost < min)
            min = cost;
    }
    return min;
}
int main()
{
    vector<int> neighbor{ 1, 2, 3 };
    cout << TSP(neighbor, 0) << endl;
    return 0;
}

In fact, the erase function removes the element j from the set (which is the neighbor vector)

I know about dynamic programming that prevents duplicate calculations (like the Fibonacci function) but it does not have duplicate calculations because if we draw the tree of this function we see that the arguments of function (i.e. S and i in formula and like the picture below) are never the same and there is no duplicate calculation. My question is, is this time O(n!)?

picture :enter image description here If yes,why? This function is exactly the same as the formula and it does exactly the same thing. Where is the problem? Is it doing duplicate calculations?

Satar
  • 37
  • 7

1 Answers1

1

Your algorithm time complexity is O(n!). It's easy to understand that your code is guessing the next node of the path. And there're exactly n! different paths. Your code actually counts the same value several times. For example if you run TSP({1, 2, 3, 4}, 0) and it tries order {1, 2, 3} and {2, 1, 3}. It is clear that code will run TSP({4}, 3) two times. To get rid of this store already calculated answers for masks and start node.

nd2003
  • 71
  • 8
  • Thanks, I got it.The only problem is that it calculates duplicates, right?isnt there any other problem? And that this code does not count as duplicates when the number of S members is 3? – Satar Dec 14 '20 at 18:02
  • That's the only problem I see. If the size of S is 3 it goes to `if (neighbor.size() == 0)` statement multiple times. – nd2003 Dec 14 '20 at 18:50
  • I do not understand what you said. But my question is if the size of the `S` is 3, except for the leaves, we do not have a repetitive calculation, right? – Satar Dec 14 '20 at 19:21
  • We do not have a repetitive calculation – nd2003 Dec 14 '20 at 19:25