Advertisement
cd62131

Tour

Jul 14th, 2014
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #include <float.h>
  2. #include <math.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. typedef struct {
  7.   char *name;
  8.   double x, y;
  9. } city_t;
  10. static city_t *new_city(char *name, double x, double y);
  11. static city_t **read_city(FILE *in, int *n);
  12. static double distance(city_t *p1, city_t *p2, city_t *p3);
  13. int main(const int argc, const char **argv);
  14. static city_t *new_city(char *name, double x, double y) {
  15.   city_t *new = (city_t *) malloc(sizeof(city_t));
  16.   new->name = (char *) malloc(strlen(name) + 1);
  17.   strcpy(new->name, name);
  18.   new->x = x;
  19.   new->y = y;
  20.   return new;
  21. }
  22. static city_t **read_city(FILE *in, int *n) {
  23.   city_t ** cities = NULL;
  24.   char name[BUFSIZ];
  25.   double x, y;
  26.   *n = 0;
  27.   while (fscanf(in, "%s%lf%lf", name, &x, &y) != EOF) {
  28.     cities = (city_t **) realloc(cities, ++(*n) * sizeof(city_t *));
  29.     cities[*n - 1] = new_city(name, x, y);
  30.   }
  31.   return cities;
  32. }
  33. static double distance(city_t *p1, city_t *p2, city_t *p3) {
  34.   return sqrt((p1->x - p2->x) * (p1->x - p2->x) + (p1->y - p2->y) * (p1->y - p2->y)) +
  35.       sqrt((p2->x - p3->x) * (p2->x - p3->x) + (p2->y - p3->y) * (p2->y - p3->y)) +
  36.       sqrt((p3->x - p1->x) * (p3->x - p1->x) + (p3->y - p1->y) * (p3->y - p1->y));
  37. }
  38. int main(const int argc, const char **argv) {
  39.   city_t ** cities;
  40.   int n, i, j, k;
  41.   double d, min = DBL_MAX;
  42.   FILE *in = fopen(argv[1], "r");
  43.   cities = read_city(in, &n);
  44.   for (i = 0; i < n; i++)
  45.     for (j = i + 1; j < n; j++)
  46.       for (k = j + 1; k < n; k++) {
  47.         d = distance(cities[i], cities[j], cities[k]);
  48.         printf("%s %s %s: %lf\n", cities[i]->name, cities[j]->name, cities[k]->name, d);
  49.         if (d < min) min = d;
  50.       }
  51.   printf("minimum: %lf\n", min);
  52.   return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement