Under construction

Still being built. Things may change

Unstacking Boxes

Time limit1sMemory limit512 MB

Summary
Boxes sit in piles in a row; a box can be removed only when it is on top and at least one side is unblocked. Find the fewest removals needed to expose box 1.
Level

Medium6 of 10

Topics
Dynamic programming, Greedy, Implementation
Solved
No attempts yet

Problem

A boy has just moved house. Before the move he packed all of his books into numbered boxes, and he wrote an inventory saying which box each book went into. He put that inventory in box 1.

In his new room he found that his parents had stacked the boxes into several piles standing in a row, with each pile touching the next one.

The boy is methodical, so he wants the inventory back before he opens any other box. He is also clumsy. To pull a box out of a pile, the box has to be on top of its pile and at least one of its two sides has to be free, which means no box touches it on that side. Either side will do.

Consider the box sitting at position hh from the bottom of the ii-th pile from the left. Its left side is blocked if pile i−1i-1 holds hh or more boxes at that moment, and free otherwise. The right side works the same way with pile i+1i+1. Nothing stands to the left of the first pile or to the right of the last pile, so those sides are always free.

The room is large, so the boy puts every box he takes out somewhere else without disturbing the piles his parents built.

Given the positions of the boxes in the piles, find the smallest number of boxes, box 1 excluded, that the boy has to take out in order to get box 1.

Input

The input holds several test cases. The first line of each test case has two integers NN and PP, the number of boxes and the number of piles (1≤P≤N≤10001 \le P \le N \le 1000). The boxes are numbered from 1 to NN.

Each of the next PP lines describes one pile, in left to right order. The ii-th of those lines starts with an integer QiQ_i, the number of boxes in pile ii, then a single blank, then QiQ_i box numbers separated by blanks. The numbers are listed from the bottom of the pile to its top.

Every pile holds at least one box, and every box appears exactly once in the whole input. All boxes have the same shape and size.

A line with NN and PP both equal to 0 marks the end of the input. That line is not a test case.

Output

For each test case print one line with a single integer: the smallest number of boxes, box 1 excluded, that the boy has to take out to get box 1.

Examples3

  1. Example 1

    Input
    4 3
    1 3
    2 1 2
    1 4
    4 3
    1 3
    2 2 1
    1 4
    0 0
    
    Expected output
    2
    0
    
  2. Example 2

    Input
    5 5
    1 5
    1 3
    1 1
    1 2
    1 4
    0 0
    
    Expected output
    2
    
  3. Example 3

    Input
    13 5
    3 2 3 4
    3 5 6 7
    3 8 1 9
    3 10 11 12
    1 13
    0 0
    
    Expected output
    3