Problem:
Problem B: Book Replacement The deadline of Prof. Hachioji’s assignment is tomorrow. To complete the task, students have
to copy pages of many reference books in the library. All the reference books are in a storeroom and only the librarian is allowed to enter it. To obtain
a copy of a reference book’s page, a student should ask the librarian to make it. The librarian
brings books out of the storeroom and makes page copies according to the requests. The overall
situation is shown in Figure 1. Students queue up in front of the counter. Only a single book can be requested at a time. If a
student has more requests, the student goes to the end of the queue after the request has been
served. In the storeroom, there are m desks D 1 , ... , D m , and a shelf. They are placed in a line in this
order, from the door to the back of the room. Up to c books can be put on each of the desks. If
a student requests a book, the librarian enters the storeroom and looks for it on D 1 , ... , D m in
this order, and then on the shelf. After finding the book, the librarian takes it and gives a copy
of a page to the student.   Then the librarian returns to the storeroom with the requested book, to put it on D 1 according to the following procedure.  If D 1 is not full (in other words, the number of books on D 1 < c ), the librarian puts the requested book there.  If D 1 is full, the librarian  temporarily puts the requested book on the non-full desk closest to the entrance or,
     in case all the desks are full, on the shelf,  finds the book on D 1 that has not been requested for the longest time (i.e. the least recently used book) and takes it,  puts it on the non-full desk (except D 1 ) closest to the entrance or, in case all the desks except D 1 are full, on the shelf,  takes the requested book from the temporary place,  and finally puts it on D 1 .   Your task is to write a program which simulates the behaviors of the students and the librarian,
and evaluates the total cost of the overall process. Costs are associated with accessing a desk
or the shelf, that is, putting/taking a book on/from it in the description above. The cost of an
access is i for desk D i and m + 1 for the shelf. That is, an access to D 1 , ... , D m , and the shelf
costs 1, ... , m , and m + 1, respectively. Costs of other actions are ignored. Initially, no books are put on desks. No new students appear after opening the library. Input The input consists of multiple datasets. The end of the input is indicated by a line containing
three zeros separated by a space. It is not a dataset. The format of each dataset is as follows.  m c n  k 1  b 11 . . . b 1 k 1 .
      .
      . k n  b n 1 . . . b nk n  Here, all data items are positive integers. m is the number of desks not exceeding 10. c is the number of books allowed to put on a desk, which does not exceed 30. n is the number of
students not exceeding 100. k i is the number of books requested by the i -th student, which does
not exceed 50. b ij is the ID number of the book requested by the i -th student on the j -th turn.
No two books have the same ID number. Note that a student may request the same book more
than once. b ij is less than 100. Here we show you an example of cost calculation for the following dataset. 3 1 2
3
60 61 62
2
70 60 In this dataset, there are 3 desks ( D 1 , D 2 , D 3 ). At most 1 book can be put on each desk. The
number of students is 2. The first student requests 3 books of which IDs are 60, 61, and 62,
respectively, and the second student 2 books of which IDs are 70 and 60, respectively. The calculation of the cost for this dataset is done as follows. First, for the first request of the
first student, the librarian takes the book 60 from the shelf and puts it on D 1 and the first
student goes to the end of the queue, costing 5. Next, for the first request of the second student,
the librarian takes the book 70 from the shelf, puts it on D 2 , moves the book 60 from D 1 to D 3 ,
and finally moves the book 70 from D 2 to D 1 , costing 13. Similarly, the cost for the books 61,
60, and 62, are calculated as 14, 12, 14, respectively. Therefore, the total cost is 58. Output  For each dataset, output the total cost of processing all the requests, in a separate line.  Sample Input  2 1 1
1
50
2 1 2
1
50
1
60
2 1 2
2
60 61
1
70
4 2 3
3
60 61 62
1
70
2
80 81
3 1 2
3
60 61 62
2
70 60
1 2 5
2
87 95
3
96 71 35
2
68 2
3
3 18 93
2
57 2
2 2 1
5
1 2 1 3 1
0 0 0  Output for the Sample Input  4
16
28
68
58
98
23

Solution (Python):
def solve():
    from collections import deque
    from sys import stdin
    f_i = stdin
    
    ans = []
    while True:
        m, c, n = map(int, f_i.readline().split())
        if m == 0:
            break
        
        book_pos = dict()
        studens = deque()
        shelf = m + 1
        
        for i in range(n):
            k = int(f_i.readline())
            books = deque(map(int, f_i.readline().split()))
            for b in books:
                book_pos[b] = shelf
            studens.append(books)
        
        desk = [0] * (m + 1) 
        D1 = deque()
        cost = 0
        
        while studens:
            s = studens.popleft()
            b = s.popleft()
            
            
            pos = book_pos[b]
            cost += pos
            if pos == 1:
                D1.remove(b)
            elif pos != shelf:
                desk[pos] -= 1
            
            if len(D1) == c:
                for i, cnt in enumerate(desk[2:], start=2):
                    if cnt < c:
                        
                        desk[i] += 1
                        book_pos[b] = i
                        cost += i
                        b_pos = i
                        break
                else:
                    
                    book_pos[b] = shelf
                    cost += shelf
                    b_pos = shelf
                    
                
                unrequested = D1.popleft()
                cost += 1
                
                if b_pos == shelf:
                    
                    book_pos[unrequested] = shelf
                    cost += shelf
                else:
                    for i, cnt in enumerate(desk[b_pos:], start=b_pos):
                        if cnt < c:
                            
                            desk[i] += 1
                            book_pos[unrequested] = i
                            cost += i
                            break
                    else:
                        
                        book_pos[unrequested] = shelf
                        cost += shelf
                
                
                if b_pos != shelf:
                    desk[b_pos] -= 1
                D1.append(b)
                book_pos[b] = 1
                cost += (b_pos + 1)
            else:
                
                D1.append(b)
                book_pos[b] = 1
                cost += 1
            
            if s:
                studens.append(s)
        
        ans.append(cost)
    
    print('\n'.join(map(str, ans)))

solve()