└── dynamic array /dynamic array: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | * This stores the total number of books in each shelf. 6 | */ 7 | int* total_number_of_books; 8 | 9 | /* 10 | * This stores the total number of pages in each book of each shelf. 11 | * The rows represent the shelves and the columns represent the books. 12 | */ 13 | int** total_number_of_pages; 14 | 15 | int main() 16 | { 17 | int total_number_of_shelves; 18 | scanf("%d", &total_number_of_shelves); 19 | 20 | int total_number_of_queries; 21 | scanf("%d", &total_number_of_queries); 22 | 23 | // Allocate memory for the total number of books per shelf 24 | total_number_of_books = calloc(total_number_of_shelves, sizeof(int)); 25 | 26 | // Allocate memory for the total number of pages per book per shelf 27 | total_number_of_pages = calloc(total_number_of_shelves, sizeof(int*)); 28 | for (int i = 0; i < total_number_of_shelves; i++) { 29 | total_number_of_pages[i] = NULL; 30 | } 31 | 32 | while (total_number_of_queries--) { 33 | int type_of_query; 34 | scanf("%d", &type_of_query); 35 | 36 | if (type_of_query == 1) { 37 | /* 38 | * Process the query of first type here. 39 | */ 40 | int x, y; 41 | scanf("%d %d", &x, &y); 42 | 43 | // Increase the count of books on shelf x 44 | total_number_of_books[x] += 1; 45 | int size = total_number_of_books[x]; 46 | 47 | // Reallocate memory to accommodate the new book 48 | total_number_of_pages[x] = realloc(total_number_of_pages[x], size * sizeof(int)); 49 | 50 | // Store the number of pages in the new book 51 | total_number_of_pages[x][size - 1] = y; 52 | 53 | } else if (type_of_query == 2) { 54 | int x, y; 55 | scanf("%d %d", &x, &y); 56 | printf("%d\n", *(*(total_number_of_pages + x) + y)); 57 | } else { 58 | int x; 59 | scanf("%d", &x); 60 | printf("%d\n", *(total_number_of_books + x)); 61 | } 62 | } 63 | 64 | if (total_number_of_books) { 65 | free(total_number_of_books); 66 | } 67 | 68 | for (int i = 0; i < total_number_of_shelves; i++) { 69 | if (*(total_number_of_pages + i)) { 70 | free(*(total_number_of_pages + i)); 71 | } 72 | } 73 | 74 | if (total_number_of_pages) { 75 | free(total_number_of_pages); 76 | } 77 | 78 | return 0; 79 | } 80 | --------------------------------------------------------------------------------