-
Notifications
You must be signed in to change notification settings - Fork 5
/
tsp-brute.cpp
executable file
·76 lines (62 loc) · 1.24 KB
/
tsp-brute.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <limits>
using namespace std;
int n;
const int nmin = 1, nmax = 64;
int cities[nmax], route[nmax];
double min_len = numeric_limits<double>::infinity();
double dist[nmax][nmax];
// Returns the full cycle length for the current permutation of cities
double route_len(const int cities[])
{
double len = 0;
for (int i = 1; i <= n; i++)
len += dist[cities[i - 1]][cities[i % n]];
return len;
}
void print_route(const int cities[])
{
for (int i = 0; i <= n; i++)
printf("%d ", cities[i % n]);
printf("\n");
}
// Recursively checks the cycle cost of all (n - 1)! city permutations
void tsp(int i = 1)
{
if (i == n) {
double len = route_len(cities);
if (len < min_len) {
copy(cities, cities+n, route);
min_len = len;
}
return;
}
for (int j = i; j < n; j++) {
swap(cities[i], cities[j]);
tsp(i+1);
swap(cities[i], cities[j]);
}
}
void read_distances()
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> dist[i][j];
}
}
}
int main(int argc, char **argv)
{
cin >> n;
read_distances();
for (int i = 0; i < n; i++)
cities[i] = i;
tsp();
print_route(route);
printf("%0.2f\n", min_len);
return 0;
}