views:

118

answers:

1

This is related to travelling salesman problem. First all permutations need to be generated and then the destination (same as origin) attached. I.e.: 1) abcd abdc ....

2) abcda abdca ....a

I have all the distances and only need an algorithm to sum them up. I wonder if there is an algorithm (C preferable) I can use for this or if there is a ready-made solution somewhere.

+2  A: 

This is kinda trivial.

int sum = 0;
for (i = 0; i < length-1; i++)
{
  sum += distance[group[i]][group[i+1]];
}

Where distance is a 2d array (matrix if you will) that holds the distance between the two nodes. group should be an array or vector or the nodes in order traveled.

If you also need to get each permutation, use next_permutation.

Here's a brief example of what distance might be:

int distance[4][4] = {
 {0,2,1,0},
 {2,0,1,2},
 {1,1,0,1},
 {0,2,1,0},
};

Note that this will be a symmetric matrix for your problem.

JoshD
What is length?
nnn
That's meant to be the length of the list of nodes. It should always be the same for your situation (5 for the example you gave).
JoshD
I'm working on a switch statement for the distance function and I don't want to type the same distances with source and destination reversed. Is there something else I can do?
nnn
Don't use a switch statement. Put the distances in a matrix (type vector<vector<int> >). Then you can just `return distances[i][i+1]`. The subscripts should be the node values. So for nodes a and b, you might do `distances[0][1]`. Furthermore, you can first put the two parameters in increasing order, so given b, a, you'd switch them to a, b.
JoshD