QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#873238 | #3445. Numbers On a Tree | fernandes_queila | RE | 0ms | 0kb | C11 | 2.9kb | 2025-01-26 10:48:49 | 2025-01-26 10:48:50 |
answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Estrutura do n\xf3 da \xe1rvore
typedef struct Node {
int label;
struct Node* left;
struct Node* right;
} Node;
// Fun\xe7\xe3o para criar um novo n\xf3
Node* create_node(int label) {
Node* new_node = (Node*)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Erro ao alocar mem\xf3ria\n");
exit(1);
}
new_node->label = label;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
// Fun\xe7\xe3o para construir a \xe1rvore bin\xe1ria perfeita e rotular n\xf3s
void build_tree(Node* root, int height) {
if (height < 0) {
return;
}
int num_leaves = 1 << height;
int root_label = (1 << (height + 1)) - 1;
int start_label = 1;
root->label = root_label;
Node** queue = (Node**)malloc(num_leaves * sizeof(Node*));
if (queue == NULL) {
printf("Erro ao alocar mem\xf3ria\n");
exit(1);
}
int front = 0;
int rear = 0;
queue[rear++] = root;
while (front < rear) {
Node* current = queue[front++];
if (current->left == NULL && current->right == NULL) {
if (start_label < root_label) {
current->left = create_node(root_label - start_label);
current->right = create_node(root_label - start_label - 1);
queue[rear++] = current->right;
queue[rear++] = current->left;
start_label += 2;
}
}
}
free(queue);
}
// Fun\xe7\xe3o para procurar o n\xf3 de acordo com o caminho
int search_node(Node* root, const char* road) {
Node* current = root;
int len = strlen(road);
for (int i = 0; i < len; i++) {
if (road[i] == 'L' || road[i] == 'l') {
if (current->left != NULL) {
current = current->left;
} else {
return -1; // Caminho inv\xe1lido
}
} else if (road[i] == 'R' || road[i] == 'r') {
if (current->right != NULL) {
current = current->right;
} else {
return -1; // Caminho inv\xe1lido
}
}
}
return current->label;
}
// Fun\xe7\xe3o para liberar a mem\xf3ria da \xe1rvore
void free_tree(Node* root) {
if (root == NULL) {
return;
}
free_tree(root->left);
free_tree(root->right);
free(root);
}
int main() {
int height;
char input[40]; // Ajuste o tamanho do buffer conforme necess\xe1rio
char road[31]; // O comprimento m\xe1ximo do caminho \xe9 30
// L\xea a entrada
fgets(input, sizeof(input), stdin);
sscanf(input, "%d %s", &height, road);
// Construir a \xe1rvore bin\xe1ria perfeita com base na altura fornecida
Node* root = create_node(0);
build_tree(root, height);
// Calcula e imprime o r\xf3tulo do n\xf3
int label = search_node(root, road);
printf("%d\n", label);
// Liberar mem\xf3ria da \xe1rvore
free_tree(root);
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Runtime Error
input:
3 LR