1436.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5. char *
  6. destCity(char*** paths, int pathsSize, int* pathsColSize) {
  7. struct {
  8. char **data;
  9. unsigned long size;
  10. unsigned long cap;
  11. } froms = {0};
  12. struct {
  13. char **data;
  14. unsigned long size;
  15. unsigned long cap;
  16. } tos = {0};
  17. froms.cap = pathsSize;
  18. froms.data = calloc(froms.cap, sizeof(*froms.data));
  19. tos.cap = pathsSize;
  20. tos.data = calloc(tos.cap, sizeof(*tos.data));
  21. for ( int i = 0; i < pathsSize; ++i ) {
  22. froms.data[froms.size++] = paths[i][0];
  23. tos.data[tos.size++] = paths[i][1];
  24. }
  25. char *ret = NULL;
  26. for ( unsigned long i = 0; i < tos.size; ++i ) {
  27. bool found = false;
  28. for ( unsigned long j = 0; j < froms.size; ++j ) {
  29. if ( strcmp(tos.data[i], froms.data[j]) == 0 ) {
  30. found = true;
  31. break;
  32. }
  33. }
  34. if ( ! found ) { ret = tos.data[i]; break; }
  35. }
  36. (void) pathsColSize;
  37. free(tos.data);
  38. free(froms.data);
  39. return ret;
  40. }
  41. char *
  42. paths_to_cstr_temp(char ***paths, int pathsSize) {
  43. static char *data = NULL;
  44. static unsigned long size = 0;
  45. static unsigned long cap = 1024;
  46. if ( data == NULL ) { data = malloc(sizeof(char) * (cap + 1)); }
  47. size = 0;
  48. memset(data, 0, cap);
  49. data[size++] = '[';
  50. for ( int i = 0; i < pathsSize; ++i ) {
  51. if ( size + 32 >= cap ) { cap = cap*2; data = realloc(data, cap*2); }
  52. if ( i > 0 ) { data[size++] = ','; }
  53. data[size++] = '[';
  54. char *from = paths[i][0];
  55. while ( *from != '\0' ) { data[size++] = *from++; }
  56. data[size++] = ',';
  57. char *to = paths[i][1];
  58. while ( *to != '\0' ) { data[size++] = *to++; }
  59. data[size++] = ']';
  60. }
  61. data[size++] = ']';
  62. data[size++] = '\0';
  63. return data;
  64. }
  65. void
  66. r(char ***paths, int pathsSize, char *exp)
  67. {
  68. printf("destCity(%s, %d) = %s | exp: %s\n",
  69. paths_to_cstr_temp(paths, pathsSize),
  70. pathsSize,
  71. destCity(paths, pathsSize, NULL),
  72. exp);
  73. }
  74. int
  75. main(void)
  76. {
  77. char *paths11[2] = {"London","New York"};
  78. char *paths12[2] = {"New York","Lima"};
  79. char *paths13[2] = {"Lima","Sao Paulo"};
  80. char **paths1[] = {paths11, paths12, paths13};
  81. r(paths1, 3, "Sao Paulo");
  82. char *paths21[2] = {"B","C"};
  83. char *paths22[2] = {"D","B"};
  84. char *paths23[2] = {"C","A"};
  85. char **paths2[] = {paths21, paths22, paths23};
  86. r(paths2, 3, "A");
  87. char *paths31[2] = {"A","Z"};
  88. char **paths3[] = {paths31};
  89. r(paths3, 1, "Z");
  90. return 0;
  91. }