Bored Dreamoon
Time limit1sMemory limit512 MB
Given soldier heights and a right-front relation matrix, find the minimum size of the front row in a valid row arrangement, or -1 if none exists.
- Level
Hard8 of 10
- Topics
- Sorting, Implementation, Greedy
- Solved
- No attempts yet
Problem
Dreamoon serves in the military this year. Everything in the military is boring. To make military life more interesting, Dreamoon decided to turn some of his military experiences into programming competition problems.
Leaders usually order soldiers to stand in several rows ordered by their heights. The arrangement rules are as follows:
- If two soldiers and stand in different rows, and 's row is in front of 's row, then is shorter than .
- If two soldiers and stand in the same row, and is to the right of , then is shorter than .
- For any two rows, the difference between the number of soldiers in them is at most .
- For any two rows, the number of soldiers in the front row is equal to or larger than the number of soldiers in the back row.
After Dreamoon noticed these properties, the following problem came to his mind.
For two different soldiers and , we say is right front of if 's row is NOT in front of 's row, and the number of soldiers to the right of in 's row is not larger than the number of soldiers to the right of in 's row.
You do not know how many soldiers there are in total, and you do not know how many rows they are arranged into. You do know the heights of soldiers, numbered from through . For any two distinct numbers and , you know whether soldier is right front of soldier . Determine whether at least one configuration satisfies the given information. If one exists, compute the minimum number of soldiers in the first row (the row in front of every other row).
Input
The first line contains one integer , the number of soldiers. The second line contains integers , where is the height of soldier . Each of the following lines contains characters. The -th character of the -th of these lines is '1' if soldier is right front of soldier , and '0' otherwise.
Output
Print one number, the minimum possible number of soldiers in the first row. If no configuration satisfies the given information, print .
Constraints
- All are distinct.
- is '0' or '1'.
- is '0' for all in .