We need to determine if we can reach a target permutation from the identity permutation by a series of swaps where each cell i can swap with cell j if |i-j| = d_i (the favorite number of cell i). The cells can move in any order, unlimited moves. So we have a set of allowed swaps between pairs (i, j) such that |i-j| = d_i (or is it also that j's favorite number matters? The problem statement: "On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell." It says "if |i - j| = di" where di is favorite of i-th cell. It does not mention condition on j's favorite. So it's an asymmetric condition? But note that swapping is symmetric: if i exchanges with j, both values are swapped. The move is performed by i-th cell. So i can initiate a swap with any j such that distance equals its d_i. It doesn't say that j must also be able to swap with i; but the swap occurs anyway. However, the rules might be interpreted as only allowed moves are those where the initiating cell satisfies the distance condition. Since moves can be made by any cell in any order, essentially if there exists a sequence of such swaps to reach target, it's allowed. But does the asymmetry matter? Typically in such problems, swapping is allowed between i and j if either i can swap with j or j can swap with i? Let's read carefully: "On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell." So it seems the move is initiated by cell i. So if we consider any swap between i and j to be possible, we need that either i can initiate (|i-j| = d_i) or j can initiate (|j-i| = d_j). Since we can choose the order, we could have i initiate a swap with j if allowed, or j initiate with i if allowed. So effectively an undirected swap is allowed if at least one of the two conditions holds. However, sometimes these problems assume symmetry: the move is a swap and the condition only on the moving cell, but since we can decide who moves, if either i or j can initiate, we can achieve the swap. But caution: if i can swap with j but j cannot swap with i, can we still swap? Yes, because we could have i make the move. So the set of possible swaps is: for any ordered pair (i, j) with |i-j| = d_i, we can swap values of i and j. But note that a swap is between two cells, so doing it from i's perspective or j's leads to same result. So the set of unordered pairs that can be swapped is those where either |i-j| = d_i or |i-j| = d_j.
But we need to think about connectivity. This is reminiscent of reachable permutations through allowed swaps; they are exactly the permutations that respect the connected components of the graph where vertices are positions and edges are allowed swaps. Because swapping values along edges generates the group of permutations within each connected component (since swaps generate the full symmetric group on the component). Actually, if the graph is connected on a set of positions, any permutation of the values among those positions is achievable by swaps (since swaps generate the symmetric group). However, there is nuance: The swaps are not necessarily reversible? But swapping is symmetric; if we can swap i and j via i's move, can we also swap them back? Possibly by having i or j again initiate. Since the condition for i to swap with j is |i-j| = d_i. That remains true after the swap? The positions remain fixed; d_i is attached to the cell (position) i, not to the value. So yes, the condition is based on positions, so the swap operation is always allowed as long as the condition holds, regardless of what values are. So the graph is static: vertices are positions 1..n, edges exist if at least one direction is allowed. Then we can apply any sequence of swaps along edges. This yields that reachable permutations are those that can be obtained by swapping elements along edges; that is exactly that the permutation must be such that each element moves only within its connected component. More precisely, if we start with identity (value i at position i), after any series of swaps, the multiset of values in each component remains the same; equivalently, for each position, the value that ends up there must be one of the values originally in that component; i.e., the permutation must map each component onto itself. In other words, the permutation is reachable if and only if for every i, i and p(i) are in the same connected component of the graph defined by allowed swaps.
Check examples: Example 1: n=5, d_i = 1 for all. So edges: |i-j| = 1 => adjacent positions can swap (both ways). Graph is a path 1-2-3-4-5, which is connected. So any permutation is reachable. Target permutation is 5 4 3 2 1 (reverse), which is within the same component. Output YES. Good.
Example 2: n=7, d = [4,6,6,1,6,6,1]; target perm: [4,3,5,1,2,7,6]. Let's compute edges. We'll check connectivity. For each i, j such that |i-j| = d_i or d_j. We'll see if the permutation sends each position to a value in the same component. Example output is NO. Let's test manually.
We'll compute components. Let positions 1..7.
d1=4: possible j: |j-1|=4 => j=5 (since 1+4=5, 1-4 negative). So edge (1,5) because d1=4 allows 1 to swap with 5. Also maybe from j's side: For j=5, d5=6; |5-1|=4, not equal to d5 (6). So only direction is 1->5, but that's enough to have edge.
d2=6: |j-2|=6 => j=8 (out of range) or j=-4, so none. So 2 cannot initiate any swap. But others might swap with 2 if they have d_j = |j-2|. For position j, if |j-2| = d_j. Let's check: j=1: |1-2|=1, d1=4 not 1. j=3: |3-2|=1, d3=6 not 1. j=4: |4-2|=2, d4=1 not 2. j=5: |5-2|=3, d5=6 not 3. j=6: |6-2|=4, d6=6 not 4. j=7: |7-2|=5, d7=1 not 5. So no edges incident to 2? But we must also consider j=8? out. So position 2 is isolated? That would mean it cannot swap with anyone, so the value at position 2 must stay 2. But target permutation has at position 2 the value 3. So would be unreachable. However output is NO, consistent.
But wait, check Example 3: same d, target permutation: [4,2,5,1,3,7,6]. Output YES. So in this case, position 2 has value 2, which is identity (2). So possible if 2 is isolated. Let's verify: In Example 2, position 2 gets 3; Example 3, position 2 gets 2. So consistent.
But we need to confirm connectivity: Is position 2 indeed isolated? Let's double-check: d2=6. The maximum distance possible within n=7 is 6. |2-?|=6 => 2+6=8 >7, 2-6=-4. So no j with distance exactly 6. Also for other positions j, condition |j-2| = d_j. Check j=1: d1=4, distance=1, no. j=3: distance=1, d3=6, no. j=4: distance=2, d4=1, no. j=5: distance=3, d5=6, no. j=6: distance=4, d6=6, no. j=7: distance=5, d7=1, no. So indeed 2 isolated. So Example 3: 2->2 works, thus maybe other parts also match.
Thus our reasoning that allowed swaps define an undirected graph (if at least one direction allows a swap) and reachable permutations are those that map each vertex to a vertex in the same component, appears correct.
But need to be careful: Could there be any extra constraints due to the asymmetry of moves? Since only one cell can initiate a swap, is it possible that even if there is a path of swaps connecting two positions, we might not be able to achieve a specific permutation because the order of swaps might require intermediate states where a particular swap is not possible due to the direction? However, since we can always choose the initiating cell, if we need to swap i and j and we have an edge (i,j) via some direction, we can do it directly. For longer sequences, we can always perform swaps along edges in any order. It's known that the set of transpositions generates the full symmetric group on each connected component, because any transposition of two vertices in the same component can be achieved via a sequence of swaps along a path: you can bubble the values along the path. For example, if we have a path a-b-c-d, we can move value from a to d by a series of swaps: swap a and b, then b and c, then c and d, then move other values back. Each swap is allowed because the edge exists. However, does direction matter? In a path a-b, if only a can swap with b but b cannot swap with a, can we still perform swap? Yes, we can have a initiate. So the edge is directed but we can use it in either direction by initiating from the appropriate endpoint. But careful: if only a can swap with b, then to swap a and b we need a to initiate. That is fine. To swap b and a later, we would also need a to initiate again. That's okay. So as long as there is at least one directed edge between a and b, we can effect the swap in both directions by using the same initiator. So it's essentially an undirected edge.
Thus the graph is undirected with edges if condition holds for at least one endpoint.
Now the problem reduces to: given n, d[1..n], and a permutation p[1..n] (p is the final state where position i contains p[i]), determine if for every i, i and p[i] are in the same connected component of the graph defined by edges (i,j) such that |i-j| = d_i or |i-j| = d_j.
Alternatively, we can compute the equivalence relation (connected components) via BFS/DFS union-find. Since n ≤ 100, trivial.
We'll implement Union-Find: For each i from 1 to n, for each j from 1 to n, if i != j and (abs(i-j) == d[i] OR abs(i-j) == d[j]), union(i,j). But careful: d[i] is 1-indexed? Input: last line contains n integers from 1 to n — favourite numbers of the cells. So d[i] between 1 and n inclusive. But distance can be up to n-1. d[i] could be n, but max distance is n-1, so if d[i]=n, there is no j such that |i-j| = n. So that's fine. So we can just loop over i and j. Complexity O(n^2) fine.
Alternatively, for each i, compute j = i + d[i] and j = i - d[i] if within [1,n], then union(i,j). But that only covers edges where the condition holds for i. However, we also need edges where condition holds for j but not i. But if we union from both sides: for each i, we can connect to i+d_i and i-d_i. But note that if j has d_j such that |i-j| = d_j, that edge may not be captured by i's direction. But if we also union j to i for that case? That would require scanning from each j. Actually, if we simply for each i, connect to i ± d_i, that captures edges where i can initiate. Since we are taking union on both ends, and if there is an edge that exists only because j can initiate, i.e., |i-j| = d_j, then when we process j, we will connect j to i (since j ± d_j includes i). So by processing all i, we will cover both directions. Because for any pair (i,j) with |i-j| = d_i, we union when processing i; if |i-j| = d_j, we union when processing j. So yes, it's sufficient to iterate over i and union with i±d_i (if valid). That yields undirected graph where edges exist if at least one direction holds.
Thus algorithm: initialize DSU (size n). For i in 1..n: if i+d_i <= n: union(i, i+d_i); if i-d_i >= 1: union(i, i-d_i).
Then for each i from 1 to n, check if find(i) == find(p[i]) (p is the target permutation). If all true, print "YES", else "NO".
Let's test examples.
Example 1: d=[1,1,1,1,1] -> unions: each i connects to i+1 and i-1 -> whole component. Permutation all in same component -> YES.
Example 2: d=[4,6,6,1,6,6,1]
i=1: d=4 -> 1+4=5 union(1,5). 1-4 negative ignore.
i=2: d=6 -> 2+6=8 ignore; 2-6 ignore.
i=3: d=6 -> 3+6=9 ignore; 3-6 ignore.
i=4: d=1 -> 4+1=5 union(4,5); 4-1=3 union(4,3). So (4,5) and (4,3). That connects 4,5,3. But note 1 is connected to 5 via i=1. So now 1,5,4,3 all connected. Also 4-3 connects 3.
i=5: d=6 -> 5+6=11 ignore; 5-6 ignore. So no new.
i=6: d=6 -> 6+6=12 ignore; 6-6=0 ignore.
i=7: d=1 -> 7-1=6 union(7,6); 7+1=8 ignore. So (7,6). So components: {1,3,4,5} and {6,7} and {2} isolated. Actually also check: from i=4 we union 4 with 3 and 5; from i=1 union 1 with5; so {1,3,4,5}. Also i=7 union 7 with6 -> {6,7}. i=2 alone.
Now target permutation: [4,3,5,1,2,7,6].
Check: pos1 contains 4. Are 1 and 4 in same component? 1 is in {1,3,4,5}, 4 is also in that component -> ok.
pos2 contains 3. 2 is isolated, 3 in {1,3,4,5}. Not same -> fails. So NO. Correct.
Example 3: target: [4,2,5,1,3,7,6].
pos2 contains 2 -> same component (both isolated) ok.
pos3 contains 5: 3 in {1,3,4,5}, 5 in same -> ok.
pos4 contains 1: both in same -> ok.
pos5 contains 3: both in same -> ok.
pos6 contains 7: 6 in {6,7}, 7 in same -> ok.
pos7 contains 6: both same -> ok.
pos1 contains 4: both same -> ok. So YES.
Thus algorithm works.
Now we must consider any tricky aspects: Input states "favourite numbers of the cells" are integers from 1 to n, not necessarily distinct. That's fine. Also note that the number of moves is unlimited, and cells make moves in any order. So indeed any permutation reachable within component.
But is there any possibility that due to the asymmetric nature, some swaps are not reversible? Actually, if only one direction allowed, then after swapping, can we swap back? Suppose only i can swap with j. After swapping, values are swapped. To swap back, we need again i to swap with j (since j cannot initiate). That is allowed because condition still holds: |i-j| = d_i. So it's reversible. So edge is effectively undirected.
Another nuance: The move says "i-th cell can exchange it's value with the value of some other j-th cell, if |i-j| = di". Does it imply that only i's value is swapped with j, and j's value becomes i's original? That's a standard swap. So yes.
Thus solution is straightforward.
But wait, what about the fact that the cell's "favourite number" might be the same as its ordinal? Not relevant.
Implementation details: Input: first line n, second line permutation (n distinct ints), third line d (n ints). Output YES/NO.
We'll implement DSU.
Edge Cases: n=1, d[1] any 1..1, identity only. The permutation must be [1] -> check if find(1)==find(p[1]) always true. So YES if p[1]=1 else NO? But permutation is from 1 to n distinct; if n=1 then p[1]=1 necessarily. So YES.
If d_i large like n, no edges.
Also note that we might get components that are not fully connected if only one direction? But our union method works.
Time complexity: O(n).
But wait, is there any scenario where the component is not fully symmetric? For example, suppose only i can swap with j and j cannot swap with i. Could we still achieve any permutation on the set {i,j}? Yes, we can swap them, and swap back. So any transposition is possible, and any permutation on two elements is either identity or swap. So full symmetric group. On larger set, if we have a directed star? But if only some directions exist, but still the underlying undirected graph is connected, then we can still perform swaps along edges by always initiating from the appropriate endpoint. However, we must ensure that we can perform any sequence of adjacent transpositions along a path. Consider a path a-b-c where edges are directed: a can swap with b, and b can swap with c, but c cannot swap with b, and b cannot swap with a? Wait we need to consider directionality: Suppose only a can swap with b (i.e., edge a->b) and only c can swap with b (c->b). So b cannot initiate swaps with either. The undirected graph is a path a-b-c. Can we achieve swapping values between a and c? Typically we would use a series: swap a and b (a initiates), then swap b and c (c initiates? But after first swap, the values at a and b are swapped. Now to swap between b and c, we need c to initiate with b. That is allowed because |c-b| = d_c? We have edge from c to b. So c can swap with b regardless of values. So yes, we can: a initiates swap with b, then c initiates swap with b, then maybe a initiates swap with b again to move value from b to a. So feasible. So any connected undirected graph with edges where at least one direction exists is sufficient for the symmetric group on the component. However, we need to consider if there is a case where to achieve a permutation we might need to swap two non-adjacent vertices directly, but we can do it via path.
But is it always true that if the undirected graph is connected, any permutation of the values on its vertices is reachable using only swaps along directed edges (where each swap uses the direction that is allowed)? I think yes because we can simulate any adjacent swap along an undirected edge by using the allowed direction. But we need to be careful: what if an edge is only allowed in one direction and we need to perform a swap along that edge in the context of moving a value from one side to the other but the allowed direction is opposite to the needed movement? But we can always achieve a swap of the values on the two vertices, regardless of which direction we use. The effect of swapping is symmetric; it doesn't matter which vertex initiates. So if we need to swap the values on the two vertices, we can just use the vertex that can initiate. So it's always possible to swap the values of any edge (undirected, meaning at least one direction exists). Therefore the set of allowed transpositions is exactly the set of edges (undirected). Then it's well-known that the group generated by transpositions along edges of a connected graph is the full symmetric group on the vertices of that graph. This is true because the graph is connected, and transpositions along edges generate the full symmetric group on the vertex set (since any transposition can be expressed as a product of edge transpositions if the graph is connected: for any two vertices u,v, there is a path; we can swap along the path to exchange u and v while keeping other values in place, using the method of bubble sort). So indeed the group is the full symmetric group. So the condition that p maps each component onto itself is necessary and sufficient.
Thus solution stands.
We'll write code.
But there is a catch: The problem statement says "Cells make moves in any order, the number of moves is unlimited." It doesn't say that cells can make multiple moves or that they can choose to not move. It's implied they can move repeatedly.
Hence final.
Let's write solution in Python.
Implementation details:
-
Read n
-
Read permutation list p (list of ints, length n)
-
Read list d (list of ints, length n)
-
Use 0-indexing for arrays but DSU with indices 0..n-1 to simplify.
-
DSU class: parent array, size/rank optional.
-
For i in range(n): if i + d[i] < n: union(i, i+d[i]) (since i+d[i] is 0-index: i+1 in 1-index terms? careful: d[i] is given in 1-indexed sense? Actually, if we treat positions 0-indexed: originally position i (0-index) had value i+1. But the favorite numbers are given for each cell, which presumably correspond to position i (1-indexed). When we convert to 0-index, the distance condition becomes |i - j| = d_i? In 1-index, condition is |i - j| = d_i. In 0-index, position index i (0-index) corresponds to cell i+1. So its favorite number d_i (the i-th integer) is still the same number. The condition becomes | (i+1) - (j+1) | = d_i => |i - j| = d_i. So it's same absolute difference of indices (since subtracting 1 each). So it's consistent: using 0-index, distance in indices equals d_i. So we can just treat indices 0..n-1 and d list as given.
Thus for i from 0 to n-1:
j = i + d[i] # if within 0..n-1? Actually d[i] is integer, i+d[i] might be up to n-1 if i+d[i] <= n-1. But careful: distance condition is |i - j| = d_i. So j = i + d_i. But this yields j = i + d_i; we need to ensure j < n. Also j = i - d_i must be >=0. So we union with i+d_i and i-d_i if within bounds.
- After building DSU, for each i in 0..n-1, we need to check if find(i) == find(p[i] - 1) because p[i] is the value (1-index) that should be at position i+1. Actually p is given as permutation of numbers 1..n, where p[i] (1-indexed reading) is the value at cell i after game? The input: second line contains n distinct integers from 1 to n — permutation. Likely they list the final array values: the i-th integer is the value at cell i. So if we read into list perm of length n (0-index), perm[i] is the value at position i (1-index originally). So we need to check that the value originally at position perm[i] (which is the number perm[i]) must be able to move to position i. But the condition is that for each position i, the value that ends up there (perm[i]) must originate from within the same component. Since initially value v is at position v. So we require that v and i are in the same component. In terms of DSU, we need find(i) == find(perm[i]-1) because perm[i] is value, which originally at position perm[i] (1-index) -> index perm[i]-1. So check same root.
Thus for i in range(n): if find(i) != find(perm[i]-1): print("NO") and exit. Else print("YES").
Test with examples:
Example 1:
n=5, perm=[5,4,3,2,1], d=[1,1,1,1,1]
0: union(0,1) from 0+1; union(0,-1) none.
1: union(1,2); union(1,0) (already)
...
All connected.
Check i=0: perm[0]=5 -> index4; find(0)=some, find(4)=same => ok.
i=1: perm[1]=4 -> index3; find(1)=same => ok...
Output YES.
Example 2 and 3 work.
Thus solution.
But we should consider if there is any nuance regarding "favourite number of each cell" possibly being different after swaps? No, it's fixed per cell.
Therefore answer is straightforward.
Given n <= 100, even O(n^3) is fine.
Now I will write the final solution.
But wait, the problem may also have interpretation that the move is that cell i can exchange its value with some j such that the distance equals its favourite number, but that move is only allowed if the cell i is making the move. However, the order of moves is arbitrary. But could there be a scenario where we need to use a cell as a "carrier" of values and that cell may be required to initiate a swap with another cell that is not directly connected? But that's covered by path.
Also, consider if a cell's favourite number changes? No.
Thus final.
We'll provide Python code.
I'll add DSU class:
class DSU:
def init(self, n):
self.parent = list(range(n))
self.rank = [0]*n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
xr = self.find(x); yr = self.find(y)
if xr == yr: return
if self.rank[xr] < self.rank[yr]:
self.parent[xr] = yr
elif self.rank[xr] > self.rank[yr]:
self.parent[yr] = xr
else:
self.parent[yr] = xr
self.rank[xr] += 1
Then main.
But note: if we use union on i ± d_i, we may double union but that's fine.
We should ensure that d_i values are interpreted as integers (they are given as integers from 1 to n). The distance condition: |i - j| = d_i. So when using 0-index, same.
Edge Cases: d_i may be 0? According to problem, from 1 to n, so >=1. Good.
Now test with n=1: d[0] maybe 1; i+1=2 out of range; i-1 negative; so no unions. DSU single element. perm[0] must be 1 (since permutation of 1). Check find(0) == find(0) -> YES. Good.
Thus finalize.
Let's produce final answer.
One more check: The problem might have a twist: the cells can make moves in any order, but each move is by a single cell. Could it be that a cell can only move when it is its turn, and the move consists of exchanging its value with another cell's value, but after the exchange, the values are swapped. That's same.
Alternatively, maybe the condition is that both cells must have the favourite number matching the distance? The statement: "if |i - j| = di, where di is a favourite number of i-th cell." It doesn't say anything about j's favourite number. So our interpretation stands.
But we need to consider if there is possibility that a swap might be disallowed if it's not i's turn? But since we can choose any order, we can choose i to move when we need that swap.
Thus correct.
Thus output solution.
Given problem is from Codeforces (maybe problem "Permutation" or "Cells"?). It's likely accepted.
I'll now produce final response. ```python
class DSU:
def init(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a, b):
ra = self.find(a)
rb = self.find(b)
if ra == rb:
return
if self.rank[ra] < self.rank[rb]:
self.parent[ra] = rb
elif self.rank[ra] > self.rank[rb]:
self.parent[rb] = ra
else:
self.parent[rb] = ra
self.rank[ra] += 1
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
n = int(next(it))
perm = [int(next(it)) for _ in range(n)]
fav = [int(next(it)) for _ in range(n)]
dsu = DSU(n)
# build graph: for each cell connect it to i +/- fav[i] (if inside bounds)
for i in range(n):
d = fav[i]
if i + d < n:
dsu.union(i, i + d)
if i - d >= 0:
dsu.union(i, i - d)
# check condition: position i and value perm[i] must be in same component
for i in range(n):
# value perm[i] originally was at index perm[i]-1
if dsu.find(i) != dsu.find(perm[i] - 1):
print("NO")
return
print("YES")
if name == "main":
solve()