Knowledge for the Masses
Time limit1sMemory limit512 MB
Each row's racks keep their order and can shift left or right at cost 1 per rack; find the cheapest passage position and all positions attaining it.
- Level
Hard8 of 10
- Topics
- Greedy, Prefix sum, Sorting, Array
- Solved
- No attempts yet
Problem
You are in a library equipped with bookracks that move on rails. There are many parallel rails, so the bookracks are organized in several rows, as shown below.

The bookracks in the library. At the moment there is no passage to the librarian.
To borrow a book you must reach the librarian, who is hiding on the far side of the bookracks. Your task is to move the racks along the rails so that a passage forms.
- Each rack has an integer width and can be placed at any integer point along its rail. (A rack is not fixed at a non-integer position and could accidentally roll either way.)
- The racks in a single row need not be contiguous: there may be arbitrary integer-sized empty space between two successive racks.
- Within a row, racks may not overlap and cannot pass through one another, so their left-to-right order never changes.
A passage forms at position if, in every row, there is no bookrack inside the interval .

Passages formed in the library: position (left figure) and position (right figure). Moving the racks marked with arrows, both are attained at cost .
Moving a rack takes effort: shifting it in either direction costs , and this cost does not depend on the shift distance (which can be explained by the well-known fact that static friction is considerably higher than kinetic friction). You are here to borrow a book, not to work out, so you would like to form a passage (at any position) with as little effort as possible.
Input
In each row, a value denotes a bookrack of width , while denotes a single unit of empty space.
- The first line contains the number of test cases (). Then test cases follow.
- The first line of each test case contains two space-separated integers and (, ): the number of rows and the common width of every row.
- Then row descriptions follow. Each starts with an integer , followed by integers separated by single spaces.
For every row , equals minus the number of that are equal to . Moreover, . Each row description contains at least one , so forming a passage is always possible.
Output
For each test case, output two lines.
- The first line contains the minimum cost of making a passage.
- The second line contains, in increasing order and separated by spaces, all positions at which a minimum-cost passage can be formed.