PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#DSU0000044. Hoán vị năm mới (New Year Permutation)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Hoán vị năm mới (New Year Permutation)

New Year Permutation

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation pp of length nn and an n×nn\times n binary matrix AA. The matrix is symmetric, so Ai,j=Aj,iA_{i,j}=A_{j,i}, and every diagonal entry is 00.

You may swap the values at two distinct positions i,ji,j whenever Ai,j=1A_{i,j}=1. These swaps may be used any number of times in any order. Swapping values changes only the permutation; the matrix AA and the allowed pairs of positions remain fixed.

Find the lexicographically smallest permutation among all reachable permutations. When comparing two permutations, the first position where their values differ determines which is smaller.

Input

The first line contains nn, the second the permutation pp, followed by nn binary strings describing the rows of AA.

Output

Print the lexicographically smallest permutation.

Subtasks

  • Subtask 1 (20 points): 1≤n≤121\le n\le12; pp is a permutation of 1,…,n1,\ldots,n; the matrix contains only 0 and 1, with Ai,j=Aj,iA_{i,j}=A_{j,i} and Ai,i=0A_{i,i}=0.
  • Subtask 2 (30 points): 1≤n≤1001\le n\le100; pp is a permutation of 1,…,n1,\ldots,n; the matrix contains only 0 and 1, with Ai,j=Aj,iA_{i,j}=A_{j,i} and Ai,i=0A_{i,i}=0.
  • Subtask 3 (50 points): 1≤n≤3001\le n\le300; pp is a permutation of 1,…,n1,\ldots,n; the matrix contains only 0 and 1, with Ai,j=Aj,iA_{i,j}=A_{j,i} and Ai,i=0A_{i,i}=0.

Examples

Input

5
4 2 1 5 3
00100
00011
10010
01101
01010

Output

1 2 3 4 5

Explanation

All positions 1,2,3,4,51,2,3,4,5 lie in the same connected component of allowable swaps. Therefore the values can be rearranged into 1 2 3 4 5, which is the lexicographically smallest permutation.