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

#FW0000035. Hoán vị đẹp nhất 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ị đẹp nhất năm mới (New Year Permutation)

New Year Permutation

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Given a permutation and a symmetric matrix of allowed swaps, perform any number of swaps and find the lexicographically smallest reachable permutation.

Input

Integer nn, a permutation p1,…,pnp_1,\ldots,p_n, then nn binary strings of length nn specifying allowed swaps.

Output

Print the lexicographically smallest reachable permutation.

Subtasks

  • Subtask 1 (40 points): n≤15n\le15; 1≤n≤3001\le n\le300; pp is a permutation of 1…n1\ldots n; the adjacency matrix is symmetric with zero diagonal.
  • Subtask 2 (60 points): 1≤n≤3001\le n\le300; pp is a permutation of 1…n1\ldots n; the adjacency matrix is symmetric with zero diagonal.

Examples

Input

4
4 3 2 1
0100
1010
0101
0010

Output

1 2 3 4

Explanation

All four positions lie in the same connected component of swappable positions. Sorting the component values produces the lexicographically smallest permutation.