66 lines
1.1 KiB
C
66 lines
1.1 KiB
C
#include "tsp.h"
|
|
|
|
static float distance(t_city a, t_city b)
|
|
{
|
|
float dx = b.x - a.x;
|
|
float dy = b.y - a.y;
|
|
return (sqrtf(dx * dx + dy * dy));
|
|
}
|
|
|
|
static float path_length(t_city *cities, int *route, int n)
|
|
{
|
|
float total = 0;
|
|
int i = 0;
|
|
|
|
while (i < n)
|
|
{
|
|
total += distance(cities[route[i]], cities[route[(i + 1) % n]]);
|
|
i++;
|
|
}
|
|
return (total);
|
|
}
|
|
|
|
static void solve(t_city *cities, int *route, int pos, int n, float *best)
|
|
{
|
|
float current;
|
|
int i, temp;
|
|
|
|
if (pos == n)
|
|
{
|
|
current = path_length(cities, route, n);
|
|
if (current < *best)
|
|
*best = current;
|
|
return;
|
|
}
|
|
i = pos;
|
|
while (i < n)
|
|
{
|
|
temp = route[pos];
|
|
route[pos] = route[i];
|
|
route[i] = temp;
|
|
solve(cities, route, pos + 1, n, best);
|
|
temp = route[pos];
|
|
route[pos] = route[i];
|
|
route[i] = temp;
|
|
i++;
|
|
}
|
|
}
|
|
|
|
int main(void)
|
|
{
|
|
t_city cities[11];
|
|
int route[11];
|
|
int n = 0;
|
|
float best = 999999.0f;
|
|
|
|
while (n < 11 && fscanf(stdin, "%f, %f", &cities[n].x, &cities[n].y) == 2)
|
|
{
|
|
route[n] = n;
|
|
n++;
|
|
}
|
|
if (n < 2)
|
|
return (1);
|
|
solve(cities, route, 0, n, &best);
|
|
fprintf(stdout, "%.2f\n", best);
|
|
return (0);
|
|
} |