pvjc26/du5/program.c
2026-04-16 15:31:30 +00:00

127 lines
2.6 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 256
typedef struct Tree {
char text[SIZE];
int isAnswer;
struct Tree *yes;
struct Tree *no;
} Tree;
// читання дерева у preorder
Tree* readTree() {
char line[SIZE];
if (fgets(line, SIZE, stdin) == NULL) return NULL;
// кінець дерева = порожній рядок
if (strcmp(line, "\n") == 0) return NULL;
// прибрати \n і \r
line[strcspn(line, "\r\n")] = 0;
Tree *node = malloc(sizeof(Tree));
node->yes = NULL;
node->no = NULL;
if (line[0] == '*') {
node->isAnswer = 1;
int i = 1;
while (line[i] == ' ') i++;
strcpy(node->text, line + i);
} else {
node->isAnswer = 0;
strcpy(node->text, line);
node->yes = readTree();
node->no = readTree();
}
return node;
}
// перевірка пустого рядка після дерева
int EmptyLine() {
char line[SIZE];
if (fgets(line, SIZE, stdin) == NULL) return 0;
return strcmp(line, "\n") == 0;
}
// підрахунок листів
int Leaves(Tree *node) {
if (!node) return 0;
if (node->isAnswer) return 1;
return Leaves(node->yes) + Leaves(node->no);
}
// звільнення пам’яті
void freeTree(Tree *node) {
if (!node) return;
freeTree(node->yes);
freeTree(node->no);
free(node);
}
// запуск системи
void start(Tree *node) {
char input[SIZE];
while (node && !node->isAnswer) {
printf("%s\n", node->text);
if (fgets(input, SIZE, stdin) == NULL) {
printf("Koniec vstupu\n");
return;
}
int i = 0;
while (input[i] == ' ' || input[i] == '\t') i++;
if (input[i] == 'a') {
node = node->yes;
} else if (input[i] == 'n') {
node = node->no;
} else {
printf("Nerozumiem\n");
return;
}
}
if (node && node->isAnswer) {
printf("* %s\n", node->text);
printf("Koniec\n");
}
}
int main() {
printf("Expert z bufetu to vie.\n");
Tree *root = readTree();
if (!root) {
printf("Chyba nacitania\n");
return 0;
}
if (!EmptyLine()) {
printf("Chyba nacitania\n");
freeTree(root);
return 0;
}
int count = Leaves(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
start(root);
freeTree(root);
return 0;
}