• + 0 comments

    Simplest solution: Prepare required storages then Perform insert (with realloc if necessary)

    Code Solution ------------------------>

    int main() ........ { int total_number_of_shelves; scanf("%d", &total_number_of_shelves);

    int total_number_of_queries;
    scanf("%d", &total_number_of_queries);
    
    //1. Prepare Storage
    total_number_of_books = (int *)malloc(total_number_of_shelves * sizeof(int));
    total_number_of_pages = (int **)malloc(total_number_of_shelves * sizeof(int*));
    
        //2. Init Storage
    for (int i = 0; i < total_number_of_shelves; i++) 
    {
        total_number_of_books[i] = 0;
        total_number_of_pages[i] = (int*)malloc(sizeof(int));
        total_number_of_pages[i][0] = 0;
    }
    
    while (total_number_of_queries--) {
        int type_of_query;
        scanf("%d", &type_of_query);
    
        if (type_of_query == 1) {
            /*
             * Process the query of first type here.
             */
            int x, y;
            scanf("%d %d", &x, &y);
    
                        //3. Insert Book
            total_number_of_books[x]++;
    
                        //4. Insert Page
            if(total_number_of_books[x] == 1)
            {
                total_number_of_pages[x][0] = y;
            }
            else 
            {
                total_number_of_pages[x] = realloc(total_number_of_pages[x], total_number_of_books[x]*sizeof(int));
                total_number_of_pages[x][total_number_of_books[x]-1] = y;
            }