Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <float.h>
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct {
- char *name;
- double x, y;
- } city_t;
- static city_t *new_city(char *name, double x, double y);
- static city_t **read_city(FILE *in, int *n);
- static double distance(city_t *p1, city_t *p2, city_t *p3);
- int main(const int argc, const char **argv);
- static city_t *new_city(char *name, double x, double y) {
- city_t *new = (city_t *) malloc(sizeof(city_t));
- new->name = (char *) malloc(strlen(name) + 1);
- strcpy(new->name, name);
- new->x = x;
- new->y = y;
- return new;
- }
- static city_t **read_city(FILE *in, int *n) {
- city_t ** cities = NULL;
- char name[BUFSIZ];
- double x, y;
- *n = 0;
- while (fscanf(in, "%s%lf%lf", name, &x, &y) != EOF) {
- cities = (city_t **) realloc(cities, ++(*n) * sizeof(city_t *));
- cities[*n - 1] = new_city(name, x, y);
- }
- return cities;
- }
- static double distance(city_t *p1, city_t *p2, city_t *p3) {
- return sqrt((p1->x - p2->x) * (p1->x - p2->x) + (p1->y - p2->y) * (p1->y - p2->y)) +
- sqrt((p2->x - p3->x) * (p2->x - p3->x) + (p2->y - p3->y) * (p2->y - p3->y)) +
- sqrt((p3->x - p1->x) * (p3->x - p1->x) + (p3->y - p1->y) * (p3->y - p1->y));
- }
- int main(const int argc, const char **argv) {
- city_t ** cities;
- int n, i, j, k;
- double d, min = DBL_MAX;
- FILE *in = fopen(argv[1], "r");
- cities = read_city(in, &n);
- for (i = 0; i < n; i++)
- for (j = i + 1; j < n; j++)
- for (k = j + 1; k < n; k++) {
- d = distance(cities[i], cities[j], cities[k]);
- printf("%s %s %s: %lf\n", cities[i]->name, cities[j]->name, cities[k]->name, d);
- if (d < min) min = d;
- }
- printf("minimum: %lf\n", min);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement