#define _POSIX_C_SOURCE 2 #include #include #include #include #include #include #include int read_line(int fd, char *buf, size_t len, int *bye) { char c; ssize_t st; if (len == 0) return 0; // precaution while ((st = read(fd, &c, 1))) { if (st < 0) return errno; if (c == '\n') break; else if (len <= 1) return -1; // buffer too small else { *buf = c; buf++; len--; } } *buf = '\0'; if (st == 0) *bye = 1; return 0; } int line_is_empty(char *data) { for(;*data != '\0'; data++) { if (!isspace(*data)) return 0; } return 1; } int parse_line(char *data, int *result) { if (data == NULL || result == NULL) return 0; char *tok; int howmany; for (howmany = 0;;howmany++) { if (!howmany) tok = strtok(data, " "); else tok = strtok(NULL, " "); if (tok == NULL) break; if (howmany > 1) return -1; // too many fields errno = 0; *result = (int) strtol(tok, NULL, 10); result++; // must be valid if (errno) return errno; } if (howmany != 2) return -2; // too few fields return 0; } int sign(long num) { if (num > 0) return 1; else if (num == 0) return 0; else return -1; } int cmp(const void *one, const void *two) { return sign(*((int *) one) - *((int *) two)); } void complain(int msg, int where) { printf("On line %d: ", where); if (msg > 0) puts(strerror(msg)); else printf("internal error: %d", msg); } int main() { char buf[1024]; int line; int bye = 0; int i[2]; int id_1[1024]; int id_2[1024]; int st; for(line = 0; line < 1024; line++) { if ((st = read_line(0, buf, 1024, &bye))) { complain(st, line + 1); return 1; } else if (line_is_empty(buf) && !bye) { line--; // 200iq continue; } if (bye) break; if ((st = parse_line(buf, i))) { complain(st, line + 1); return 1; } id_1[line] = i[0]; id_2[line] = i[1]; } qsort(id_1, line, sizeof(int), cmp); qsort(id_2, line, sizeof(int), cmp); int sum = 0; for (int iter = 0; iter < line; iter++) { sum += id_2[iter] - id_1[iter]; } printf("Total distance is %d\n", sum); }