A permutation is a list of K numbers, each between 1 and K (both inclusive), that has no duplicate elements.
Permutation X is lexicographically smaller than Permutation Y if for some i ≤ K:
All of the first i-1 elements of X are equal to first i-1 elements of Y.
ith element of X is smaller than ith element of Y.
You are given a permutation P, you can exchange some of its elements as many times as you want in any order. You have to find the lexicographically smallest Permutation that you can obtain from P.
K is less than 101.
Input Format:
First line of input contains K being the size of permutation.
Next line contains K single spaced numbers indicating the permutation.
Each of next K lines contains K characters, character j of line i is equal to 'Y' if you can exchange i;th and j;th element of a permutation, and 'N' otherwise.
Output Format:
Print K numbers with a space separating each of them indicating the permutation.
SAMPLE INPUT
3
3 2 1
NYN
YNY
NYN
SAMPLE OUTPUT
1 2 3
Explanation
first can be exchanged with second. So, from 3 2 1 , we can get 2 3 1. 2 3 1 is
lexicographically smaller than 3 2 1. Matrix also says the second the third element can be swapped.
From this we get, 2 1 3. 2 1 3 is lexicographically smaller than 2 3 1. As the matrix says the first and the
second element can be swapped, we get 1 2 3 from 2 1 3 and hence the answer 1 2 3.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to understand the problem: We are given a permutation P of size K (K<101). We are allowed to exchange elements as many times as we want, but exchanges are only allowed between pairs (i,j) if the matrix has 'Y' at (i,j) (and presumably symmetric? The matrix lines: each of next K lines contains K characters, character j of line i is 'Y' if you can exchange i-th and j-th element. It is likely symmetric but not necessarily? Usually in such problems, the exchange ability is symmetric (if you can exchange i and j, you can also exchange j and i), but the input might not guarantee symmetry? However typical problem: we have a graph where vertices are positions 1..K, edges indicate allowed swaps. Swaps can be applied arbitrarily many times, which means we can permute the elements within each connected component arbitrarily (since the group generated by transpositions on a set is the full symmetric group on each connected component). Indeed, swapping allowed edges allows us to reorder items arbitrarily within each connected component (since transpositions generate the full symmetric group). So we can achieve any permutation that reorders the values among positions in the same component. The goal: find lexicographically smallest permutation reachable.
Thus the solution: Identify connected components of the graph (positions 1..K with edges where M[i][j]=='Y'). For each component, we have a set of positions and the values currently occupying those positions (the values from P). To achieve lexicographically smallest overall permutation, we want as small as possible in the earliest positions. Since we can reorder values within a component arbitrarily, we can assign the smallest values in that component to the smallest positions within that component (by index) to minimize lexicographic order. However, careful: Because components are independent (we cannot move values across components). So the lexicographically smallest permutation is obtained by, for each component, sort the values in that component and assign them to the positions in that component in increasing order (so that the smallest position in the component gets the smallest value, etc). This yields the globally smallest lexicographic order given constraints.
Proof: Consider any position i from 1 to K. The value at position i belongs to its component. The set of values that can be placed at i are exactly the values currently in that component. To minimize lexicographically, we want the smallest possible value at position 1, but we must respect component constraints: position 1 can only get values from its component. So we assign the smallest value in that component to position 1. Then for position 2, if it's in the same component as position 1, we have already assigned some value to position 1, but we can choose the smallest remaining value from that component to position 2, which is optimal because any alternative assignment that puts a larger value at position 2 while keeping same at position 1 would be lexicographically larger. If position 2 is in a different component, we cannot affect its values by assignments to position 1's component. So we need to assign the smallest value from that component to position 2, etc. Since components are independent, the greedy approach works.
Thus algorithm: read K, permutation P (list of length K). Read K lines of length K: adjacency matrix. Build graph: for each i, for each j>i if M[i][j]=='Y', add undirected edge. Use DSU or DFS to find components. For each component, collect indices and the values at those indices from P. Sort the indices (they are naturally maybe unsorted but we need to assign sorted values to sorted indices). Sort the values in ascending order. Then for each component, for each position index in sorted order, assign the corresponding sorted value. Finally output the resulting array.
Check sample: K=3, P=[3,2,1], matrix: row1: N Y N -> edges (1,2). row2: Y N Y -> edges (2,1) and (2,3). row3: N Y N -> edges (3,2). So component includes all positions (1-2-3 connected). So all three values can be permuted arbitrarily. Sorted values: [1,2,3]; assign to positions 1,2,3 sorted -> [1,2,3]. Output matches.
Edge cases: The matrix may have 'Y' for i=j? Usually no or ignored. We can ignore diagonal. Also the matrix lines may not have spaces; they are just strings of length K. So read each line as a string. Graph is undirected: if M[i][j]=='Y', we consider both directions, but we only need to add edge for both. However input may be asymmetric, but logically if you can exchange i and j, then you can exchange j and i, so it should be symmetric. But if it's not, we can treat as undirected: we can still swap i and j if either direction says Y? Usually the problem says character j of line i is 'Y' if you can exchange i-th and j-th element, implying that the exchange operation is symmetric: swapping i and j is the same as swapping j and i. So the matrix might be symmetric but we can assume it's symmetric. To be safe, we can treat an edge if M[i][j]=='Y' or M[j][i]=='Y', but reading all lines we can just add edge when we see M[i][j]=='Y' and i!=j. This yields a directed graph but transpositions generate group on strongly connected components of the directed graph? Actually if we have a directed ability: we can exchange i and j only if allowed by matrix at (i,j)? But exchange is a symmetric operation; typically the condition is that you can swap the elements at positions i and j. The statement: "character j of line i is equal to 'Y' if you can exchange i-th and j-th element of a permutation, and 'N' otherwise." It doesn't explicitly say symmetric, but exchanging i-th and j-th is same as exchanging j-th and i-th, so it would be natural that the matrix is symmetric. So we can assume symmetry.
Given K<101, we can use simple BFS/DFS.
Complexities: O(K^2) to read matrix + O(K log K) for sorting each component values, total fine.
Now we must produce output as K numbers separated by spaces.
Implementation steps:
Read integer K.
Read line with K numbers: list P.
For i in range(K): read line as string s. If line might have spaces? The problem says "K characters", so no spaces. Possibly there are spaces? We'll read line and strip whitespace, then take each character. Ensure length is K. For each j, if s[j]=='Y' and i!=j, add edge between i and j (0-index or 1-index? We'll use 0-index for simplicity).
Build adjacency list: For each edge, add neighbor.
Find components using visited boolean array of size K.
For each node not visited, do DFS/BFS to collect all indices in component. Append to component list.
For each component, let indices = list of positions (0-index). Let values = [P[i] for i in indices]. Sort indices (they are numbers). Sort values. Then for each idx, sorted_idx = sorted_indices? Actually we want to assign the smallest value to the smallest index within component. So we sort indices ascending, and sort values ascending. Then iterate over pairs: for pos, val in zip(sorted_indices, sorted_values): assign result[pos] = val.
Output result list with spaces.
Potential pitfalls: If components are isolated, we sort values, but there is only one value. So works.
Check with custom test: K=4, P=[4,3,2,1], matrix: edges (1,2) and (3,4) only. Then components: {1,2} with values [4,3] sorted values [3,4] -> assign to positions 1,2: pos1=3, pos2=4; component {3,4} values [2,1] sorted [1,2] -> assign pos3=1, pos4=2. Result: [3,4,1,2]. But is that lexicographically smallest? Let's see alternative: Could we get [3,4,1,2] vs maybe [3,4,2,1]? The lexicographically smallest should have as small as possible at position1: within component {1,2} smallest possible is 3 (since values are 4 and 3). So position1=3. Then position2 must get the remaining from that component, which is 4. Position3: component {3,4} smallest possible is 1. So assign 1. Then position4 gets 2. So yes, result [3,4,1,2]. Good.
Now, if there is a component with positions not contiguous, e.g., positions 1,5,2 in one component. Sorting positions ascending yields smallest positions get smallest values, which is lexicographically optimal. Because earlier positions get smallest possible from that component.
Thus solution is correct.
Now, the problem might be about "you can exchange some of its elements as many times as you want in any order." This suggests that any sequence of allowed swaps is allowed. That indeed allows any permutation within each connected component (the graph of allowed swaps). So solution stands.
Implementation details in Python:
def solve():
import sys
data = sys.stdin.read().strip().splitlines()
if not data: return
K = int(data[0].strip())
P = list(map(int, data[1].split()))
# Ensure len(P)==K
adj = [[] for _ in range(K)]
for i in range(K):
line = data[2+i].strip()
for j, ch in enumerate(line):
if ch == 'Y' and i != j:
adj[i].append(j)
visited = [False]*K
res = [0]*K
for i in range(K):
if not visited[i]:
# BFS/DFS to collect component
stack = [i]
visited[i] = True
comp = []
while stack:
node = stack.pop()
comp.append(node)
for nb in adj[node]:
if not visited[nb]:
visited[nb] = True
stack.append(nb)
# comp now has indices
indices = sorted(comp)
vals = sorted([P[idx] for idx in comp])
for idx, val in zip(indices, vals):
res[idx] = val
print(' '.join(map(str, res)))
Testing with sample: should output 1 2 3.
Edge cases: When reading lines, there could be spaces? But description says "K characters", so likely no spaces. But just in case, we can strip and treat as string, ignoring spaces. Use line.replace(' ', '')? Not needed.
Also note: Input may have extra blank lines. Using sys.stdin.read().splitlines() will ignore trailing newline but include empty lines if present? Better to read lines with sys.stdin.readline in a loop.
Alternatively:
import sys
def solve():
K = int(sys.stdin.readline())
P = list(map(int, sys.stdin.readline().split()))
adj = [[] for _ in range(K)]
for i in range(K):
line = sys.stdin.readline().strip()
# In case line may have spaces: remove spaces
line = line.replace(' ', '')
for j, ch in enumerate(line):
if ch == 'Y' and i != j:
adj[i].append(j)
visited = [False]*K
res = [0]*K
for i in range(K):
if not visited[i]:
comp = []
stack = [i]
visited[i] = True
while stack:
node = stack.pop()
comp.append(node)
for nb in adj[node]:
if not visited[nb]:
visited[nb] = True
stack.append(nb)
indices = sorted(comp)
vals = sorted(P[idx] for idx in comp)
for idx, val in zip(indices, vals):
res[idx] = val
print(' '.join(map(str, res)))
That should be fine.
Complexity: O(K^2) due to reading matrix and building adjacency (max edges O(K^2)). DFS O(K+E). Sorting each component values O(K log K). All fine.
Now think about whether the ability to exchange elements as many times as we want in any order implies that we can apply any transposition within the connected component? For an undirected graph, transpositions along edges generate the full symmetric group on each connected component. This is because any permutation can be expressed as product of transpositions of adjacent elements, and using a spanning tree you can simulate adjacent swaps. More formally, the graph is connected, so you can move any element to any position through series of swaps; thus you can achieve any rearrangement. Yes.
So solution correct.
Now check if any nuance: The problem statement: "You can exchange some of its elements as many times as you want in any order." This might be interpreted as: you can pick any pair (i,j) for which exchange is allowed, and swap those elements. You can do this repeatedly. That's exactly the same.
Therefore we implement as described.
Now produce final answer. ```python
import sys
def solve() -> None:
# ----- read input -----
K_line = sys.stdin.readline()
if not K_line:
return
K = int(K_line.strip())
P = list(map(int, sys.stdin.readline().split()))
code
# adjacency list for positions 0 .. K-1
adj = [[] for _ in range(K)]
for i in range(K):
line = sys.stdin.readline().strip()
# remove possible spaces, just in case
line = line.replace(' ', '')
for j, ch in enumerate(line):
if ch == 'Y' and i != j:
adj[i].append(j)
visited = [False] * K
ans = [0] * K
for start in range(K):
if visited[start]:
continue
# ----- collect one connected component -----
stack = [start]
visited[start] = True
comp = []
while stack:
v = stack.pop()
comp.append(v)
for nb in adj[v]:
if not visited[nb]:
visited[nb] = True
stack.append(nb)
# ----- assign smallest values to smallest indices -----
sorted_indices = sorted(comp)
sorted_values = sorted(P[i] for i in comp)
for idx, val in zip(sorted_indices, sorted_values):
ans[idx] = val
# ----- output -----
print(' '.join(map(str, ans)))