#define MAX_K 4
#define MAX_HEIGHT 32
#define DEBUG 0 // Cambia a 1 para habilitar los mensajes de depuración
typedef struct {
unsigned char *T; // Bitmap del árbol
unsigned char *L; // Bitmap de las hojas
int n; // Dimensión de la matriz
int k; // Valor de k para k^2
int height; // Altura del árbol
int t_len; // Número total de bits en T
int l_len; // Número total de bits en L
} K2Tree;
// Prototipos de funciones
void build_tree(K2Tree *tree, int **matrix, int size, int row, int col, int level);
int has_one(int **matrix, int size, int row, int col);
int int_pow(int base, int exp);
int log_base_k(int n, int k);
int k2_tree_access(K2Tree *tree, int row, int col);
void free_k2_tree(K2Tree *tree);
int ceil_div(int a, int b);
void set_bit(unsigned char *bitmap, int pos);
int get_bit(unsigned char *bitmap, int pos);
// Variables globales para mantener el índice actual en T y L durante la construcción
int T_bits_count = 0;
int L_bits_count = 0;
// Funciones utilitarias
int ceil_div(int a, int b) {
return (a + b - 1) / b;
}
int log_base_k(int n, int k) {
int log = 0;
while (n > 1) {
n = ceil_div(n, k);
log++;
}
return log;
}
void set_bit(unsigned char *bitmap, int pos) {
bitmap[pos / 8] |= (1 << (7 - (pos % 8))); // Bit más significativo primero
}
int get_bit(unsigned char *bitmap, int pos) {
return (bitmap[pos / 8] >> (7 - (pos % 8))) & 1; // Bit más significativo primero
}
int int_pow(int base, int exp) {
int result = 1;
while (exp) {
if (exp & 1) result *= base;
base *= base;
exp >>= 1;
}
return result;
}
// Crear un k^2-tree a partir de una matriz de adyacencia
K2Tree *create_k2_tree(int **matrix, int n, int k) {
K2Tree *tree = malloc(sizeof(K2Tree));
if (!tree) {
fprintf(stderr, "Error al asignar memoria para K2Tree.\n");
exit(EXIT_FAILURE);
}
tree->n = n;
tree->k = k;
tree->height = log_base_k(n, k);
code
Assistant
// Calcular el número total de bits en T y L
tree->t_len = 0; // Se calculará durante la construcción
tree->l_len = 0; // Se calculará durante la construcción
// Estimar el tamaño máximo necesario para T y L (asignación inicial)
int max_nodes = (int_pow(k * k, tree->height) - 1) / (k * k - 1);
int max_T_bits = max_nodes * k * k;
int max_L_bits = int_pow(k * k, tree->height);
tree->T = calloc((max_T_bits + 7) / 8, sizeof(unsigned char));
tree->L = calloc((max_L_bits + 7) / 8, sizeof(unsigned char));
if (!tree->T || !tree->L) {
fprintf(stderr, "Error al asignar memoria para T o L.\n");
free(tree->T);
free(tree->L);
free(tree);
exit(EXIT_FAILURE);
}
if (DEBUG) printf("Creando k^2-tree: n=%d, k=%d, height=%d\n", n, k, tree->height);
// Inicializar contadores de bits
T_bits_count = 0;
L_bits_count = 0;
// Construir el árbol recursivamente
build_tree(tree, matrix, n, 0, 0, 0);
// Ajustar longitud real de T y L
tree->t_len = T_bits_count;
tree->l_len = L_bits_count;
return tree;
}
void build_tree(K2Tree *tree, int **matrix, int size, int row, int col, int level) {
if (DEBUG) printf("Construyendo nivel %d en posición (%d, %d) con tamaño %d\n", level, row, col, size);
code
if (size == 1 || level == tree->height) {
// Nivel de hoja
if (has_one(matrix, size, row, col)) {
set_bit(tree->L, L_bits_count);
if (DEBUG) printf("Estableciendo bit de hoja en posición %d\n", L_bits_count);
}
L_bits_count++;
return;
}
int any_child_set = 0;
int k = tree->k;
int new_size = ceil_div(size, k);
int positions[k * k]; // Para almacenar las posiciones de hijos en T
int count = T_bits_count;
T_bits_count += k * k; // Reservar espacio para los bits de este nodo
// Inicializar bits de los hijos en 0
for (int i = 0; i < k * k; i++) {
positions[i] = count + i;
}
// Recorremos los hijos
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
int new_row = row + i * new_size;
int new_col = col + j * new_size;
// Verificar límites
int actual_size = new_size;
if (new_row + actual_size > tree->n) actual_size = tree->n - new_row;
if (new_col + actual_size > tree->n) actual_size = tree->n - new_col;
if (has_one(matrix, actual_size, new_row, new_col)) {
set_bit(tree->T, positions[i * k + j]);
any_child_set = 1;
build_tree(tree, matrix, actual_size, new_row, new_col, level + 1);
} else {
// Necesitamos incrementar L_bits_count aunque no haya un 1, para mantener la posición correcta
if (level + 1 == tree->height) {
L_bits_count++;
}
}
}
}
if (!any_child_set) {
// Si ningún hijo tiene un 1, revertimos el incremento de T_bits_count
T_bits_count -= k * k;
}
}
int has_one(int **matrix, int size, int row, int col) {
for (int i = row; i < row + size && i < size; i++) {
for (int j = col; j < col + size && j < size; j++) {
if (matrix[i][j]) return 1;
}
}
return 0;
}
int k2_tree_access(K2Tree *tree, int row, int col) {
int index = 0;
int pos_in_T = 0;
int k = tree->k;
int size = tree->n;
code
for (int level = 0; level < tree->height; level++) {
size = ceil_div(size, k);
int i = (row / size) % k;
int j = (col / size) % k;
int child = i * k + j;
pos_in_T = index + child;
if (DEBUG) printf("Nivel %d: size=%d, i=%d, j=%d, child=%d, pos_in_T=%d\n", level, size, i, j, child, pos_in_T);
if (pos_in_T >= tree->t_len || !get_bit(tree->T, pos_in_T)) {
return 0; // No existe la arista
}
index = tree->k * tree->k * (pos_in_T + 1);
// Si estamos en el último nivel, revisamos en L
if (level == tree->height - 1) {
int pos_in_L = pos_in_T - tree->t_len + L_bits_count;
return get_bit(tree->L, pos_in_L);
}
}
return 0; // No encontramos la arista
}
// Función para liberar el k^2-tree
void free_k2_tree(K2Tree *tree) {
free(tree->T);
free(tree->L);
free(tree);
}
// Función principal para pruebas
int main() {
int n = 8;
int k = 2;
code
// Crear una matriz de adyacencia de ejemplo
int **matrix = malloc(n * sizeof(int *));
if (!matrix) {
fprintf(stderr, "Error al asignar memoria para la matriz.\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < n; i++) {
matrix[i] = calloc(n, sizeof(int));
if (!matrix[i]) {
fprintf(stderr, "Error al asignar memoria para matrix[%d].\n", i);
for (int j = 0; j < i; j++) {
free(matrix[j]);
}
free(matrix);
exit(EXIT_FAILURE);
}
}
// Establecer algunas aristas
matrix[0][2] = 1;
matrix[1][3] = 1;
matrix[2][4] = 1;
matrix[3][5] = 1;
matrix[4][6] = 1;
matrix[5][7] = 1;
// Imprimir la matriz original
printf("Matriz original:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\n");
// Crear el k^2-tree
K2Tree *tree = create_k2_tree(matrix, n, k);
// Imprimir los bitmaps T y L
printf("Bitmap T: ");
for (int i = 0; i < tree->t_len; i++) {
printf("%d", get_bit(tree->T, i));
}
printf("\nBitmap L: ");
for (int i = 0; i < tree->l_len; i++) {
printf("%d", get_bit(tree->L, i));
}
printf("\n\n");
// Probar la función de acceso
printf("Resultados de acceso en el k^2-tree:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int exists = k2_tree_access(tree, i, j);
printf("%d ", exists);
}
printf("\n");
}
// Liberar memoria
free_k2_tree(tree);
for (int i = 0; i < n; i++) {
free(matrix[i]);
}
free(matrix);
return 0;
Here's the corrected and complete code for the k²-tree implementation:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_K 4
#define MAX_HEIGHT 32
#define DEBUG 0 // Change to 1 to enable debugging messages
typedef struct {
unsigned char *T; // Bitmap of the tree
unsigned char *L; // Bitmap of the leaves
int n; // Dimension of the matrix
int k; // Value of k for k^2
int height; // Height of the tree
int t_len; // Total number of bits in T
int l_len; // Total number of bits in L
} K2Tree;
// Function prototypes
void build_tree(K2Tree *tree, int **matrix, int n, int row, int col, int level);
int has_one(int **matrix, int n, int size, int row, int col);
int int_pow(int base, int exp);
int log_base_k(int n, int k);
int k2_tree_access(K2Tree *tree, int row, int col);
void free_k2_tree(K2Tree *tree);
int ceil_div(int a, int b);
void set_bit(unsigned char *bitmap, int pos);
int get_bit(unsigned char *bitmap, int pos);
void precompute_cumulative_bits(K2Tree *tree);
// Variables for maintaining the current index in T and L during construction
int T_bits_count = 0;
int L_bits_count = 0;
// Variables for cumulative bits per level
int *cumulative_T_bits;
// Utility functions
int ceil_div(int a, int b) {
return (a + b - 1) / b;
}
int log_base_k(int n, int k) {
int log = 0;
while (n > 1) {
n = ceil_div(n, k);
log++;
}
return log;
}
void set_bit(unsigned char *bitmap, int pos) {
bitmap[pos / 8] |= (1 << (7 - (pos % 8))); // Most significant bit first
}
int get_bit(unsigned char *bitmap, int pos) {
return (bitmap[pos / 8] >> (7 - (pos % 8))) & 1; // Most significant bit first
}
int int_pow(int base, int exp) {
int result = 1;
while (exp) {
if (exp & 1) result *= base;
base *= base;
exp >>= 1;
}
return result;
}
// Create a k^2-tree from an adjacency matrix
K2Tree *create_k2_tree(int **matrix, int n, int k) {
K2Tree *tree = malloc(sizeof(K2Tree));
if (!tree) {
fprintf(stderr, "Error allocating memory for K2Tree.\n");
exit(EXIT_FAILURE);
}
tree->n = n;
tree->k = k;
tree->height = log_base_k(n, k);
// Precompute cumulative bits per level
cumulative_T_bits = malloc((tree->height + 1) * sizeof(int));
if (!cumulative_T_bits) {
fprintf(stderr, "Error allocating memory for cumulative_T_bits.\n");
free(tree);
exit(EXIT_FAILURE);
}
cumulative_T_bits[0] = 0;
for (int l = 0; l < tree->height; l++) {
cumulative_T_bits[l + 1] = cumulative_T_bits[l] + int_pow(k * k, l) * k * k;
}
tree->t_len = cumulative_T_bits[tree->height]; // Total bits in T
// Total leaves in L
tree->l_len = int_pow(k * k, tree->height);
// Allocate memory for T and L
tree->T = calloc((tree->t_len + 7) / 8, sizeof(unsigned char));
tree->L = calloc((tree->l_len + 7) / 8, sizeof(unsigned char));
if (!tree->T || !tree->L) {
fprintf(stderr, "Error allocating memory for T or L.\n");
free(tree->T);
free(tree->L);
free(tree);
free(cumulative_T_bits);
exit(EXIT_FAILURE);
}
if (DEBUG) printf("Creating k^2-tree: n=%d, k=%d, height=%d\n", n, k, tree->height);
// Initialize bit counters
T_bits_count = 0;
L_bits_count = 0;
// Build the tree recursively
build_tree(tree, matrix, n, 0, 0, 0);
return tree;
}
void build_tree(K2Tree *tree, int **matrix, int n, int row, int col, int level) {
if (DEBUG) printf("Building level %d at position (%d, %d) with size %d\n", level, row, col, n);
int k = tree->k;
if (n <= 1 || level == tree->height - 1) {
// Leaf level: collect bits into L
int new_size = ceil_div(n, k);
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
int new_row = row + i * new_size;
int new_col = col + j * new_size;
int actual_size = new_size;
if (new_row >= tree->n || new_col >= tree->n)
continue;
if (new_row + actual_size > tree->n)
actual_size = tree->n - new_row;
if (new_col + actual_size > tree->n)
actual_size = tree->n - new_col;
if (has_one(matrix, tree->n, actual_size, new_row, new_col)) {
set_bit(tree->L, L_bits_count);
}
if (DEBUG) printf("Setting leaf bit at position %d\n", L_bits_count);
L_bits_count++;
}
}
return;
}
// Internal node: create k*k children
int any_child_set = 0;
int new_size = ceil_div(n, k);
int positions[k * k]; // Positions of child bits in T
int count = T_bits_count;
T_bits_count += k * k; // Reserve space for this node's bits
for (int i = 0; i < k * k; i++) {
positions[i] = count + i;
}
// Traverse children
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
int new_row = row + i * new_size;
int new_col = col + j * new_size;
int actual_size = new_size;
if (new_row >= tree->n || new_col >= tree->n)
continue;
if (new_row + actual_size > tree->n)
actual_size = tree->n - new_row;
if (new_col + actual_size > tree->n)
actual_size = tree->n - new_col;
if (has_one(matrix, tree->n, actual_size, new_row, new_col)) {
set_bit(tree->T, positions[i * k + j]);
any_child_set = 1;
build_tree(tree, matrix, actual_size, new_row, new_col, level + 1);
} else {
// Even if no '1's, we need to maintain L_bits_count at leaf level
if (level + 1 == tree->height - 1) {
L_bits_count += k * k;
}
}
}
}
}
int has_one(int **matrix, int n, int size, int row, int col) {
for (int i = row; i < row + size && i < n; i++) {
for (int j = col; j < col + size && j < n; j++) {
if (matrix[i][j]) return 1;
}
}
return 0;
}
int k2_tree_access(K2Tree *tree, int row, int col) {
int k = tree->k;
int size = tree->n;
int index = 0; // Position in T
int offset = 0; // Offset for current level in T
for (int level = 0; level < tree->height; level++) {
size = ceil_div(size, k);
int i = (row / size) % k;
int j = (col / size) % k;
int child = i * k + j;
int pos_in_T = offset + child;
if (DEBUG) printf("Level %d: size=%d, i=%d, j=%d, child=%d, pos_in_T=%d\n", level, size, i, j, child, pos_in_T);
if (pos_in_T >= tree->t_len || !get_bit(tree->T, pos_in_T)) {
return 0; // Edge does not exist
}
if (level == tree->height - 1) {
// Next level is leaves, read from L
int pos_in_L = (pos_in_T - cumulative_T_bits[tree->height - 1]) * k * k + child;
if (pos_in_L >= tree->l_len) return 0;
return get_bit(tree->L, pos_in_L);
}
// Update offset for next level
offset = cumulative_T_bits[level + 1] + (pos_in_T - cumulative_T_bits[level]) * k * k;
}
return 0; // Edge not found
}
// Function to free the k^2-tree
void free_k2_tree(K2Tree *tree) {
free(tree->T);
free(tree->L);
free(tree);
free(cumulative_T_bits);
}
// Main function for testing
int main() {
int n = 8;
int k = 2;
// Create an example adjacency matrix
int **matrix = malloc(n * sizeof(int *));
if (!matrix) {
fprintf(stderr, "Error allocating memory for the matrix.\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < n; i++) {
matrix[i] = calloc(n, sizeof(int));
if (!matrix[i]) {
fprintf(stderr, "Error allocating memory for matrix[%d].\n", i);
for (int j = 0; j < i; j++) {
free(matrix[j]);
}
free(matrix);
exit(EXIT_FAILURE);
}
}
// Set some edges
matrix[0][2] = 1;
matrix[1][3] = 1;
matrix[2][4] = 1;
matrix[3][5] = 1;
matrix[4][6] = 1;
matrix[5][7] = 1;
// Print the original matrix
printf("Original matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\n");
// Create the k^2-tree
K2Tree *tree = create_k2_tree(matrix, n, k);
// Print the bitmaps T and L
printf("Bitmap T: ");
for (int i = 0; i < tree->t_len; i++) {
printf("%d", get_bit(tree->T, i));
}
printf("\nBitmap L: ");
for (int i = 0; i < tree->l_len; i++) {
printf("%d", get_bit(tree->L, i));
}
printf("\n\n");
// Test the access function
printf("Access results in the k^2-tree:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int exists = k2_tree_access(tree, i, j);
printf("%d ", exists);
}
printf("\n");
}
// Free memory
free_k2_tree(tree);
for (int i = 0; i < n; i++) {
free(matrix[i]);
}
free(matrix);
return 0;
}
Explanation of Corrections:
Alignment of Positions in T and L:
The main issue was the misalignment of positions in the bitmaps T and L. In the original code, T_bits_count was decremented when no child had a '1', causing incorrect positions in T.
The corrected code always reserves k*k bits for each internal node, regardless of whether any of its children have '1's. This ensures that the positions in T are consistent and predictable.
Handling of Leaf Level:
The leaf level (when level == tree->height - 1) is now correctly handled by collecting bits directly into L. Each leaf node has k*k bits corresponding to the small submatrices at the deepest level.
In the original code, there was confusion between T and L at the leaf level. The corrected code clearly separates the internal nodes (in T) from the leaf nodes (in L).
Calculation of Positions during Access:
A cumulative cumulative_T_bits array is introduced to keep track of the total number of bits in T up to each level. This allows for accurate calculation of positions during the access function.
The access function k2_tree_access is updated to correctly navigate T and L using the cumulative bits, ensuring that the correct bits are accessed based on the calculated positions.
Boundary Checks and Size Adjustments:
The functions now correctly handle matrix boundaries and adjust the sizes and positions accordingly to prevent out-of-bounds access.
The has_one function now receives tree->n to accurately check the boundaries of the matrix.
Consistency in Naming and Parameters:
Consistent variable names and parameter passing improve code readability and prevent confusion.
The functions now explicitly pass necessary parameters, such as tree->n, to ensure that all boundary conditions are correctly handled.
Memory Management:
Proper memory allocation and deallocation ensure that there are no memory leaks.
The free functions are updated to free all allocated memory, including the array.
Output of the Corrected Code:
When you run the corrected code, you should get the following (or similar) output: