Risk

Interview

Time limit3sMemory limit128 MB

Summary
not used
Level

Medium7 of 10

Topics
Graph
Solved
No attempts yet

Problem

Risk is a famous board game played on a map of the world. The world is divided by borders into several territories, and each territory belongs to exactly one player. Every territory you own must always be garrisoned by at least one of your armies.

On your turn, you may leave each army where it is or move it one step into an adjacent territory that you own. A single army may move only once, from the territory it occupies at the start of your turn to an adjacent territory; it cannot travel two or more steps in a row. You may, however, perform such moves for as many armies as you like, and you may split the armies of one territory among several destinations. You may never move every army out of a territory, leaving it with a garrison of 0. If you have no army to move, you may simply pass.

A common strategy is to mass as many armies as possible in the territories that touch enemy territory. This turn you want to make your weakest territory, the enemy-adjacent territory holding the fewest armies, as strong as possible. When your turn ends, what is the largest number of armies that can be garrisoned in your weakest territory?

Input

The first line contains the number of test cases TT (1≤T≤1001 \le T \le 100).

Each test case is given as follows.

  • The first line contains the total number of territories nn (1≤n≤1001 \le n \le 100).
  • The next line contains nn integers a1,a2,…,ana_1, a_2, \dots, a_n (0≤ai≤1000 \le a_i \le 100), where aia_i is the number of your armies garrisoned in territory ii. If aia_i is 00, that territory is held by the enemy.
  • Then nn lines follow, each consisting of nn characters 'Y' or 'N'. The jj-th character of the ii-th line is 'Y' if territories ii and jj are adjacent and 'N' otherwise. The adjacency is always symmetric, and the ii-th character of the ii-th line is 'N' for every ii.

In every test case you own at least one territory, the enemy owns at least one territory, and at least one of your territories is adjacent to an enemy territory.

Output

For each test case, print on its own line the largest number of armies that can be garrisoned in the weakest territory (the enemy-adjacent territory of yours that holds the fewest armies).

Examples3

  1. Example 1

    Input
    2
    3
    1 1 0
    NYN
    YNY
    NYN
    7
    7 3 3 2 0 0 5
    NYNNNNN
    YNYYNNN
    NYNYYNN
    NYYNYNN
    NNYYNNN
    NNNNNNY
    NNNNNYN
    
    Expected output
    1
    4
    
  2. Example 2

    Input
    1
    2
    1 0
    NY
    YN
    
    Expected output
    1
    
  3. Example 3

    Input
    1
    3
    3 1 0
    NYY
    YNY
    YYN
    
    Expected output
    2