Under construction

Still being built. Things may change

Bored Dreamoon

Time limit1sMemory limit512 MB

Summary
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 AA and BB stand in different rows, and AA's row is in front of BB's row, then AA is shorter than BB.
  • If two soldiers AA and BB stand in the same row, and AA is to the right of BB, then AA is shorter than BB.
  • For any two rows, the difference between the number of soldiers in them is at most 11.
  • 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 AA and BB, we say BB is right front of AA if AA's row is NOT in front of BB's row, and the number of soldiers to the right of BB in BB's row is not larger than the number of soldiers to the right of AA in AA'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 NN soldiers, numbered from 11 through NN. For any two distinct numbers ii and jj, you know whether soldier jj is right front of soldier ii. 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 NN, the number of soldiers. The second line contains NN integers h1,h2,…,hNh_1, h_2, \ldots, h_N, where hih_i is the height of soldier ii. Each of the following NN lines contains NN characters. The jj-th character of the ii-th of these lines is '1' if soldier jj is right front of soldier ii, 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 −1-1.

Constraints

  • 2≤N≤1032 \le N \le 10^3
  • 1≤hi≤1091 \le h_i \le 10^9
  • All hih_i are distinct.
  • sijs_{ij} is '0' or '1'.
  • siis_{ii} is '0' for all ii in 1,2,…,N1, 2, \ldots, N.

Examples2

  1. Example 1

    Input
    3
    1 2 3
    000
    000
    000
    
    Expected output
    3
    
  2. Example 2

    Input
    3
    1 2 3
    000
    100
    110
    
    Expected output
    1