229A.md (2116B)
1 Source: https://codeforces.com/problemset/problem/229/A 2 3 A. Shifts 4 5 time limit per test 6 7 2 seconds 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 stdin 16 17 output 18 19 stdout 20 21 You are given a table consisting of *n* rows and *m* columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. 22 23 To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". 24 25 Determine the minimum number of moves needed to make some table column consist only of numbers 1. 26 27 Input 28 29 The first line contains two space-separated integers: *n* (1 ≤ *n* ≤ 100) — the number of rows in the table and *m* (1 ≤ *m* ≤ 104) — the number of columns in the table. Then *n* lines follow, each of them contains *m* characters "0" or "1": the *j*-th character of the *i*-th line describes the contents of the cell in the *i*-th row and in the *j*-th column of the table. 30 31 It is guaranteed that the description of the table contains no other characters besides "0" and "1". 32 33 Output 34 35 Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. 36 37 Examples 38 39 Input 40 41 ``` 42 3 6 43 101010 44 000100 45 100000 46 ``` 47 48 Output 49 50 ``` 51 3 52 ``` 53 54 Input 55 56 ``` 57 2 3 58 111 59 000 60 ``` 61 62 Output 63 64 ``` 65 -1 66 ``` 67 68 Note 69 70 In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. 71 72 In the second sample one can't shift the rows to get a column containing only 1s.