Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

91 lines
2.5KB

  1. //
  2. // Created by red on 07/12/19.
  3. //
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #define CHUNK_SIZE 16
  7. typedef struct node {
  8. int label;
  9. struct node** children;
  10. size_t num_children;
  11. } node;
  12. typedef struct forest {
  13. int* list_labels; // list of all node labels that exist somewhere in the tree
  14. size_t num_nodes; // amount of nodes
  15. struct node** trees;
  16. size_t num_trees;
  17. } forest;
  18. //return a zero-initialized node
  19. node* init_node(int label) {
  20. node* v = malloc(sizeof(node));
  21. v->num_children = 0;
  22. v->children = calloc(CHUNK_SIZE, sizeof(node*));
  23. v->label = label;
  24. return v;
  25. }
  26. void add(node* head, node* child, int label_parent) {
  27. if (head->label == label_parent) {
  28. if (head->num_children >= CHUNK_SIZE) printf("Max number of children reached, array reallocation not implemented\n");
  29. head->children[head->num_children] = child;
  30. head->num_children++;
  31. } else for (size_t i = 0; i < head->num_children; i++) {
  32. add(head->children[i], child, label_parent);
  33. }
  34. }
  35. void print_tree(node* head) {
  36. if (head->num_children == 0) {
  37. printf("Node %x, no children\n", head->label); return;
  38. }
  39. printf("Children of node %x:", head->label);
  40. for (size_t i = 0; i < head->num_children; i++) {
  41. printf(" %x", head->children[i]->label);
  42. }
  43. printf("\n");
  44. for (size_t i = 0; i < head->num_children; i++) {
  45. print_tree(head->children[i]);
  46. }
  47. }
  48. node* read_file(char* filename) {
  49. FILE* file = fopen(filename, "r");
  50. char desc_str[7];
  51. fscanf(file, "%s", desc_str);
  52. int label_parent = (desc_str[0] << 16) + (desc_str[1] << 8) + desc_str[2];
  53. int label = (desc_str[4] << 16) + (desc_str[5] << 8) + desc_str[6];
  54. node* head = init_node(label_parent);
  55. add(head, init_node(label), label_parent);
  56. for (;;) {
  57. if (fscanf(file, "%s", desc_str) == EOF) break;
  58. label_parent = (desc_str[0] << 16) + (desc_str[1] << 8) + desc_str[2];
  59. label = (desc_str[4] << 16) + (desc_str[5] << 8) + desc_str[6];
  60. add(head, init_node(label), label_parent);
  61. if (head->label == label) {
  62. node* nhead = init_node(label_parent);
  63. add(nhead, head, label_parent);
  64. head = nhead;
  65. }
  66. }
  67. return head;
  68. }
  69. int count_nodes(node* head, int depth) {
  70. int sum = depth;
  71. for (size_t i = 0; i < head->num_children; i++) {
  72. sum += count_nodes(head->children[i], depth+1);
  73. }
  74. return sum;
  75. }
  76. int main(int argc, char **argv) {
  77. char* filename = argv[1];
  78. node* head = read_file(filename);
  79. int orbits = count_nodes(head, 0);
  80. print_tree(head);
  81. printf("no. orbits: %d\n", orbits);
  82. }