We are given t test cases. For each, we have array a of length n and a set of positions p_i (1-indexed). For each position p in the set, we can swap a[p] and a[p+1] any number of times (like an allowed adjacent swap at that specific edge). We can apply operations arbitrarily often and in any order. The question: Is it possible to sort the array (non-decreasing) using only these swaps?
This is essentially a graph/connectivity problem: We have n positions 1..n. The allowed swaps correspond to edges (p, p+1). These edges form a graph on vertices (indices). Swaps generate permutations that are reachable via swapping elements along edges that are allowed. The group of permutations reachable is the set of permutations that can be performed by exchanging elements along the connected components of the graph (i.e., within each connected component of the graph formed by allowed adjacent edges, we can arbitrarily permute the elements? Actually, the allowed operations are swapping adjacent positions that have an edge. This is like having a graph that is a set of disjoint intervals (since edges are only between consecutive indices). If we have allowed edges at certain positions, then the graph of indices with these edges is a union of segments: indices that are connected via a path of allowed adjacent swaps. For example, if allowed edges at positions 1,2,..., then indices 1,2,3,... become connected. However, if an edge is missing at position k, then the graph is split between indices <= k and indices > k? Actually, vertices are indices; edges exist between i and i+1 if and only if i ∈ p (i is in the set of allowed swap positions). So the graph is a set of connected components, each component being a contiguous segment of indices where all edges between consecutive indices within that segment are allowed. But careful: For a segment of indices from L to R to be connected, we need that for every i in [L, R-1], the edge (i,i+1) is allowed (i.e., i ∈ p). If any edge is missing, it breaks connectivity. So the components are maximal intervals such that all positions between consecutive indices are present in p. In other words, consider the sorted p positions. They might not be contiguous. For example, p = [1,3] for n=4 gives edges at (1,2) and (3,4). So connectivity: vertices: 1-2 connected via edge 1; 3-4 connected via edge 3; 2 and 3 not connected because edge (2,3) is not allowed. So components: {1,2} and {3,4}. So indeed components are contiguous segments.
Now, within each connected component, we can reorder arbitrarily? Since we only have adjacent swaps on the edges inside that component, and the component is a path graph. The allowed swaps generate the full symmetric group on that set of positions because we can bubble sort: we can move any element to any other position within the component using adjacent swaps. However, is that always true? For a path graph, the group generated by adjacent transpositions is the full symmetric group on the vertices. Indeed, the adjacent transpositions (i,i+1) for i in a contiguous set generate the symmetric group of that set. This is a classic fact: adjacent swaps generate all permutations. But we need to ensure that all those adjacent swaps are available: for a contiguous set from L to R, we have edges (i,i+1) for all i from L to R-1. So yes, we have the full set of adjacent transpositions for that segment, thus any permutation of the elements at indices L..R can be achieved. So within each component, we can rearrange the elements arbitrarily.
Thus, the overall reachable states: we can permute elements arbitrarily within each component, but cannot move elements between components.
Thus, the array can be sorted if and only if for each component, the multiset of elements originally in that component equals the multiset of elements that should be in that component in the sorted array (since we cannot move across components). But wait: is that sufficient? Yes, because if each component contains exactly the set of numbers that belong to its positions in sorted order, then we can rearrange internally to place them correctly. However, we must also consider that within each component, we can assign the elements to positions arbitrarily. So the condition is: For each connected component (contiguous segment), when we take the positions in that component, the set of values that appear originally in those positions should be exactly the same as the set of values that appear in those positions in the sorted array (i.e., after sorting the whole array). This is equivalent to saying that sorting is possible if and only if the array, after sorting, does not require moving an element across a "gap" where no swap is allowed.
So algorithm: For each test case:
-
Input n, m, array a (list of n ints), list p (positions allowed to swap, 1-indexed). m is number of allowed positions.
-
Construct a boolean array allowed of size n (or n-1) where allowed[i] = True if i+1 (or edge between i and i+1) is allowed. For convenience, we can use indices from 0 to n-2 representing edge between i and i+1 (0-indexed positions: edge between i and i+1 corresponds to original position p_i? Actually careful: The problem uses 1-indexed positions: p_i means you can swap a[p_i] and a[p_i+1]. So for i from 1 to n-1, edge at index i corresponds to being allowed. We'll store an array "can_swap" of length n (index from 1 to n) or easier: have an array "connected" that indicates if the edge between position i and i+1 (1-indexed) is allowed. We'll create a boolean array edge_allowed of size n (1-indexed, indices 1..n-1). Initialize all to False. For each p_i, set edge_allowed[p_i] = True.
-
Determine components: Iterate i from 1 to n-1, if edge_allowed[i] then indices i and i+1 are connected, so we merge; else break component. We'll compute segments: Start comp_start = 1; then for i from 1 to n-1, if edge_allowed[i] is true, continue; else the component ends at i, meaning indices from comp_start to i form a component (since there is no edge across i to i+1). Then set comp_start = i+1. After loop, there is a final component from comp_start to n.
-
For each component segment [l, r] (inclusive, 1-indexed), extract the subarray of original a at those positions, and extract the subarray of sorted a at those positions. Then sort both (or compare multisets). If they are identical, continue; else answer NO.
-
If all components pass, answer YES.
Because n ≤ 100, we can simply sort the whole array and then compare slices.
Edge Cases: If p is empty? But problem states 1 ≤ m < n, so m>=1, so p not empty? Actually m < n, but could be 0? The constraint says 1 ≤ m < n, so m >=1. So p always non-empty. But we handle general.
Complexity: O(t * n log n) which is fine.
Check examples:
Example 1: n=3, a=[3,2,1], p=[1,2] -> edges at 1 and 2. So all edges allowed, single component [1,3]. Sorted array is [1,2,3]. Original multiset in component is {3,2,1} equals sorted multiset {1,2,3} -> YES.
Example 2: n=4, a=[4,1,2,3], p=[3,2]? Actually p is [3,2] sorted? They gave p = [3,2] but order doesn't matter. So edges at 2 and 3. Edge 2 connects 2-3, edge 3 connects 3-4. Edge 1 missing. So components: Check edges: edge_allowed[1]=false, so component1: indices 1 only. edge_allowed[2]=true, edge_allowed[3]=true, so indices 2-4 connected. components: {1}, {2,3,4}. Original a: [4,1,2,3]. Sorted a: [1,2,3,4]. For component {1}: original values: [4], sorted should have value at pos1: 1 -> different, so NO. Correct.
Example 3: n=5, a=[1,2,3,4,5], p=[1]. Edge at 1 only. So components: edge1 true, but edge2 false, edge3 false, edge4 false. So actually component1: indices 1-2 (since edge1 connects 1 and 2, but edge2 missing so it stops at index2). Then indices 3 alone, 4 alone, 5 alone? Actually after component1, comp_start = 3; check edge2 false -> component2: index 3; then edge3 false -> component3: index4; edge4 false -> component4: index5. So four components. Original a is sorted already. Sorted array same. For each component, original subarray matches sorted subarray (since they are identical). So YES.
Example 4: n=4, a=[2,1,4,3], p=[1,3]. Edges: 1 true, 2 false? Actually p includes 1 and 3, so edge2 is false. So components: indices 1-2 (since edge1 true, edge2 false -> component1:1,2); indices 3-4 (since edge3 true, edge4 false? Actually edge4 is index4? No edges only up to n-1=3, so edge3 true, then end? After component starting at 3, we go to i=3? Actually we process edges: after edge1 true, we continue until hit missing edge. edge1 true, then check edge2: false -> component1 = [1,2]. Next start=3. edge2 is false we already passed; we now check edge3: true, then i goes to end (since i from 3 to n-1=3 only). After loop, component from start=3 to n=4 is component2: [3,4]. Original: [2,1,4,3]; sorted: [1,2,3,4]. For component1 (positions 1,2): original multiset {2,1} equals sorted multiset {1,2} -> yes. For component2 (positions 3,4): original {4,3} equals sorted {3,4} -> yes. So YES.
Example 5: n=4, a=[4,3,2,1], p=[1,3]. components same as above. Sorted: [1,2,3,4]. For component1: original {4,3} but sorted should be {1,2} -> not equal. So NO.
Example 6: n=5, a=[2,1,2,3,3], p=[1,4]. edges: 1 true, 2 false, 3 false, 4 true? Actually edges positions: 1 and 4. So edge1 true, edge2 false, edge3 false, edge4 true. But careful: n=5, edges positions 1,2,3,4. So we have edges at 1 and 4. So components: Check edge1 true, but edge2 false -> component1: indices 1-2? Since edge1 true connects 1-2, but edge2 false means 2 and 3 not connected, so component1 = [1,2]. Next start=3; edge2 false we already processed; now edge3 false? Actually we need to see: after start=3, we check edge3? Edge3 is false, so component2: indices 3 alone (since edge3 false breaks). Then start=4; check edge4 true, and that's the last edge, so component3: indices 4-5 (since edge4 true connects 4-5). So components: [1,2], [3], [4,5]. Original a: [2,1,2,3,3]; sorted: [1,2,2,3,3]. For component1: indices1,2: original multiset {2,1} sorted should be {1,2} -> equal (both have 1 and 2). component2: index3: original {2} sorted should be {2} -> equal. component3: indices4,5: original {3,3} sorted should be {3,3} -> equal. So YES.
Thus matches.
So approach is correct.
Implementation details: Since n <= 100, we can just simulate.
Pseudo:
def solve():
read t
for each test:
read n,m
read list a (size n)
read list p (size m)
allowed = [False]*(n) # index from 0 to n-1 representing edge between i and i+1? Use 0-index for edges: edge i between i and i+1 (0-indexed) corresponds to 1-indexed position i+1.
For each pos in p:
allowed[pos-1] = True # because pos-1 is index for edge between pos-1 and pos? Actually careful: For position p (1-indexed), it allows swapping a[p] and a[p+1]. So edge index = p-1 if we use 0-index for edges (i from 0 to n-2: edge between i and i+1). So store allowed[p-1] = True.
# Determine components
comps = [] # list of (l,r) inclusive, 0-indexed?
i=0
while i < n:
start = i
# expand while edge between current and next is allowed
while i < n-1 and allowed[i]:
i += 1
# now i is such that either i == n-1 or allowed[i] == False
# component includes indices from start to i (inclusive)
comps.append((start, i))
i += 1
# Sort a to get target sorted array
sorted_a = sorted(a)
# For each component, compare slices
ok = True
for (l,r) in comps:
orig_vals = a[l:r+1]
target_vals = sorted_a[l:r+1]
if sorted(orig_vals) != sorted(target_vals): # we could just compare sorted lists, but target_vals already sorted in global order but not necessarily sorted within the component? Actually target_vals is slice of sorted_a, which is globally sorted. But within the component, sorted_a[l:r+1] is sorted non-decreasing. But the multiset condition is that the multisets are equal. So we can compare sorted(orig_vals) to target_vals? Not exactly: target_vals is sorted, but if we sort orig_vals and compare to target_vals, they should be equal if multisets equal. But careful: target_vals is sorted; sorted(orig_vals) will be sorted. So we can compare sorted(orig_vals) == target_vals. However, if we want to be safe, we can compare sorted(orig_vals) and sorted(target_vals). But sorted(target_vals) = target_vals because target_vals is already sorted. So okay.
# Alternatively compare Counter or just sort both.
if sorted(orig_vals) != target_vals:
ok = False
break
print("YES" if ok else "NO")
But note: In condition, we need multiset equality, not necessarily that the sorted slice of original equals the sorted slice of the whole array? Actually yes, because the target sorted array positions are exactly what we need to place in that component. So sorted(orig_vals) must equal sorted_a[l:r+1] (which is sorted). That ensures the component can be rearranged to match the sorted order. However, consider a scenario: original component has values that match the multiset of the target component but maybe the global sorted array's positions within that component are not exactly the sorted order of the component's multiset? Actually, if the array is globally sorted, then the values occupying positions l..r are the smallest r-l+1 elements? Not exactly; they are the values that belong there based on the global order. Since the array is sorted, the values at positions l..r are exactly the sorted list of the multiset of values that should occupy those positions. So indeed, sorted_a[l:r+1] is a sorted list of the multiset of those values. So checking sorted(original slice) equals sorted_a[l:r+1] is correct.
But be careful: For the condition we need: For each component, the multiset of values originally in that component must equal the multiset of values that appear in those positions in the sorted array. Since we can reorder arbitrarily within the component, we can arrange them to match the sorted order if and only if those multisets are equal. So we compare two multisets: one from original a[l:r+1] and one from sorted_a[l:r+1]. So the easiest is to sort both slices and compare. Since sorted_a[l:r+1] is already sorted, we can sort original slice and compare to that. Or we can compare Counters. That's fine.
Edge Cases: For components that are singletons, condition holds trivially if the element equals the sorted element? Actually if it's a singleton, multiset equality reduces to a[l] == sorted_a[l]. So checking sorted slices works: sorted(original) will be [a[l]], target will be [sorted_a[l]], so compare.
Thus algorithm is correct.
But wait: Is the group generated by adjacent swaps within a component truly the full symmetric group? Yes, because the set of adjacent transpositions (i,i+1) for all i from L to R-1 generate S_{R-L+1}. So we can achieve any permutation. Thus we can rearrange the elements arbitrarily within the component. So condition is necessary and sufficient.
Complexities: t ≤ 100, n ≤ 100, so trivial.
Thus solution.
Potential pitfalls: The p values may not be sorted, but we mark allowed edges. The component detection uses while loops properly. Ensure we treat indices correctly.
We also must read input carefully.
Now, the problem might be a known Codeforces problem: "Swaps" maybe? I recall a problem "Swaps" or "Sorting by Swaps" with allowed edges. Yes it's a typical problem.
Thus produce final answer.
But let's double-check with all testcases from examples.
Write out steps for each example as sanity.
Example 1: n=3, allowed: edges at 1 and 2 -> allowed[0]=True, allowed[1]=True. i=0, start=0, while i<2 and allowed[0] true => i=1, while i<2 and allowed[1] true => i=2 (i now =2, i<2? i=2, not less than 2, break). comp = (0,2) i+=1 => i=3, loop ends. comps [(0,2)]. sorted_a = [1,2,3]. orig slice = [3,2,1] sorted => [1,2,3] equals target [1,2,3] -> YES.
Example 2: n=4, p=[3,2] -> positions 2 and 3 -> allowed[1]=True, allowed[2]=True (since pos-1: 2->1? Actually pos=2 => index1, pos=3 => index2). allowed[0]=False. i=0 start=0; while i<3 and allowed[0]? false, so break loop. comp (0,0). i=1. start=1; while i<3 and allowed[1]? true => i=2; while i<3 and allowed[2]? true => i=3; break because i=3 not <3. comp (1,3). i=4. done. comps: [0,0] and [1,3]. sorted_a = [1,2,3,4]. comp0: l=0,r=0: orig slice [4] sorted => [4]; target [1] => not equal -> NO.
Example 3: n=5, p=[1] -> allowed[0]=True. i=0 start=0; while i<4 and allowed[0] true => i=1; now i<4 and allowed[1] false -> break. comp (0,1). i=2 start=2; while i<4 and allowed[2] false -> break. comp (2,2). i=3 start=3; while i<4 and allowed[3] false -> break. comp (3,3). i=4 start=4; while i<4 false -> comp (4,4). comps: (0,1),(2,2),(3,3),(4,4). sorted_a = [1,2,3,4,5]. comp0: orig [1,2] sorted [1,2] target [1,2] -> ok. comp1: orig [3] -> ok, comp2: [4] ok, comp3: [5] ok -> YES.
Example 4: n=4, p=[1,3] -> allowed[0]=True, allowed[2]=True? pos=1 => index0, pos=3 => index2. allowed[1]=False. i=0 start=0; while i<3 and allowed[0] true => i=1; now i<3 and allowed[1] false -> break. comp (0,1). i=2 start=2; while i<3 and allowed[2] true => i=3; break. comp (2,3). comps: (0,1) and (2,3). orig a=[2,1,4,3]; sorted=[1,2,3,4]. comp0: orig [2,1] sorted [1,2] target [1,2] ok; comp1: orig [4,3] sorted [3,4] target [3,4] ok -> YES.
Example 5: n=4, p=[1,3] same components, orig [4,3,2,1] sorted [1,2,3,4]. comp0 orig [4,3] sorted [3,4]? Actually orig [4,3] sorted => [3,4]; target comp0 is sorted[0:2] = [1,2] -> not equal -> NO.
Example 6: n=5, p=[1,4] -> allowed[0]=True, allowed[3]=True (since pos=4 => index3). allowed[1]=False, allowed[2]=False. i=0 start=0; while i<4 and allowed[0] true => i=1; i<4 and allowed[1] false -> break. comp (0,1). i=2 start=2; while i<4 and allowed[2] false -> break. comp (2,2). i=3 start=3; while i<4 and allowed[3] true => i=4; break. comp (3,4). comps: (0,1),(2,2),(3,4). orig [2,1,2,3,3] sorted [1,2,2,3,3]. comp0: orig [2,1] sorted [1,2] target [1,2] ok. comp1: orig [2] target [2] ok. comp2: orig [3,3] target [3,3] ok -> YES.
All correct.
Thus answer.
One might also notice that the condition can be checked differently: The array is sortable if there is no inversion that crosses a forbidden boundary. But our approach is simpler and correct.
Given constraints small, we can also brute force BFS/DFS, but no need.
Hence, code accordingly.
Now implement.
We must handle multiple test cases.
Potential nuance: The p_i are distinct, but that doesn't affect.
Now code in Python.
Read input: Use sys.stdin.read().split() for speed.
Implement solve().
Plan:
def solve():
import sys
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it)); m = int(next(it))
a = [int(next(it)) for __ in range(n)]
p = [int(next(it)) for __ in range(m)]
allowed = [False] * (n-1) # edges between i and i+1 for i=0..n-2
for pos in p:
allowed[pos-1] = True
comps = []
i = 0
while i < n:
start = i
while i < n-1 and allowed[i]:
i += 1
# component from start to i inclusive
comps.append((start, i))
i += 1
sorted_a = sorted(a)
ok = True
for l, r in comps:
if sorted(a[l:r+1]) != sorted_a[l:r+1]:
ok = False
break
out_lines.append("YES" if ok else "NO")
sys.stdout.write("\n".join(out_lines))
Edge Cases: If n=1? But constraint says m < n and n>=2? Actually 1 ≤ m < n, so n must be at least 2 because m≥1 and m<n. So n>=2. But code would also work for n=1.
However, note: allowed length n-1, if n=1 then no allowed, but not needed.
So fine.
Now test with given sample.
We'll produce final answer.
Now, before final answer, let's consider possible pitfalls: The condition that we can sort if each component's elements multiset matches the target is sufficient but is there any nuance about stability or about the ability to achieve any permutation? In a path graph with all adjacent swaps available, yes, we can generate the full symmetric group. But note: The operations are only swapping a[p] and a[p+1] for p in the set. If we have a component that is a path with all edges allowed, we can perform any permutation by bubble sort: we can move any element to any position by repeated adjacent swaps, as the adjacent swaps generate the symmetric group. So correct.
Another nuance: Could there be an issue with duplicate values? Since swaps are allowed, duplicate values don't affect. The condition of multiset equality works fine.
Thus answer is correct.
Now finalize solution.
But note: There is an alternative approach: sort the array and check for each i if a[i] > a[i+1] and the swap is not allowed, then answer NO. That would also work: if we can swap adjacent only at certain positions, the array is sortable iff the relative order of elements that are not connected by allowed swaps cannot be inverted? Let's think: The condition that each component's multiset matches target is equivalent to saying that for every forbidden edge (i,i+1) that is not allowed, the prefix up to i should already be sorted relative to the suffix? Actually, if there is a forbidden edge at position i, then elements cannot cross that boundary. So all elements originally on the left of that boundary must be ≤ all elements originally on the right? Not exactly; the condition is that the left side multiset must be exactly the elements that belong to left side in sorted order. But if we think globally, after sorting, all elements on left side are ≤ any on right side. So if we cannot move elements across the boundary, we require that the maximum on left ≤ minimum on right? Actually stronger: The sorted array's left part consists of the smallest k elements. So the multiset on left must be exactly the k smallest. That implies that every element on left is ≤ every element on right? If the multiset of left is the k smallest, then indeed max(left) ≤ min(right). But the condition max(left) ≤ min(right) is necessary but not sufficient: It ensures that left side values are all ≤ right side values, but it does not guarantee that left side multiset equals the k smallest. For instance, left side values {1,3}, right side values {2,4}. max left=3, min right=2, so 3 > 2, so fails. If we had left {1,4} and right {2,3}, max left=4, min right=2, 4>2 fails. But if left {2,3} and right {1,4}, max left=3, min right=1, condition holds (3>1? Actually max left=3, min right=1, 3>1, but that violates the condition that all left ≤ all right? No, 3 > 1 is not a violation because we need left ≤ right? Actually sorted order says left elements should be ≤ right elements. So we need left elements <= right elements. 3 > 1 means left has an element 3 > right has 1, that is allowed because we don't need left <= right in the sense of every left <= every right? Actually for sorted array, all elements in left segment are ≤ all elements in right segment because the entire array is non-decreasing: the largest left element ≤ smallest right element. So condition is max(left) ≤ min(right). In example left {2,3}, right {1,4}, max left=3, min right=1, 3 ≤ 1 is false, so fails. So if left and right are such that max(left) > min(right), then they cannot be separated; but if max(left) ≤ min(right), then left consists of some values that are all ≤ right values, but does it guarantee that left multiset is exactly the smallest k? Not necessarily: consider n=4, left positions 1-2, right 3-4. Suppose sorted array is [1,2,3,4]. The left smallest are 1 and 2. If we have left {1,3} and right {2,4}, then max left=3, min right=2 => 3>2, fails. If left {1,2} and right {3,4} obviously works. But could there be left {1,1} and right {1,2}? Then max left=1, min right=1, holds, and left multiset is {1,1} while the two smallest are {1,1} indeed, so works. Could we have left {1,3} and right {2,4}? Already fails max left > min right. Could we have left {2,3} and right {1,4}? fails. Could we have left {1,4} and right {2,3}? fails. So maybe max(left) ≤ min(right) is equivalent to left containing exactly the k smallest? Let's examine: Suppose we have total multiset of numbers. Partition into left of size k and right of size n-k. If max(left) ≤ min(right), then all elements in left are ≤ all elements in right. That implies that the k smallest elements (by sorted order) are all in left? Actually if left contains all elements that are ≤ some value, but if there is any element in right that is smaller than some element in left, then condition fails. So condition ensures that the left set consists of the smallest k elements? Suppose we have numbers: [1,2,2,3]. k=2, left set could be {1,2} and right {2,3}: max left=2, min right=2, condition holds (2 ≤ 2). left is indeed the two smallest? The two smallest are 1 and 2 (but there are two 2's). left {1,2} is the multiset of the two smallest? Actually sorted: [1,2,2,3]; smallest two are 1 and 2 (the first 2). So left = {1,2} works. Could we have left = {1,3} and right = {2,2}? max left=3, min right=2, 3>2 fails. Could we have left = {2,2} and right = {1,3}? max left=2, min right=1, 2>1 fails. So maybe max(left) ≤ min(right) is sufficient to guarantee that left multiset equals the k smallest? Let's think: The condition says all elements in left are ≤ all elements in right. So if we sort the entire array, the sorted order will have all left elements before any right elements because left ≤ right. However, there could be ties: if max(left) = min(right), then there may be elements equal to that value in both sides. But the sorted order will have some of those equal values on the left and some on the right. The left could have, say, left = {1,3} and right = {2,4}? That fails because 3 > 2. So not. Let's try to find a counterexample where max(left) ≤ min(right) but left is not the k smallest. Suppose total multiset = [1,2,3,4,5,5]; k=3. Could left = {1,2,5} and right = {3,4,5}? max left=5, min right=3, 5>3 fails. Could left = {1,2,4} and right = {3,5,5}? max left=4, min right=3, 4>3 fails. Could left = {1,2,3} and right = {4,5,5} works obviously. Could left = {1,2,2} and right = {2,3,4}? max left=2, min right=2, holds. But are the three smallest numbers? Sorted: [1,2,2,2,3,4]; the three smallest are 1,2,2. left {1,2,2} indeed. Could we have left = {1,2,4} and right = {2,3,5}? max left=4, min right=2, 4>2 fails. So maybe indeed the condition max(left) ≤ min(right) is equivalent to left containing exactly the k smallest? Let's prove: Suppose we have a multiset S of size n, and we partition it into L and R with |L|=k. If max(L) ≤ min(R), then all elements of L are ≤ all elements of R. In sorted order of S, the first k elements are the k smallest. Since every element in L is ≤ every element in R, all elements in L appear before any element of R in the sorted order, so the first k positions in sorted order must be exactly the elements of L (maybe with order but same multiset). This holds because if we take the sorted list, the smallest k elements will be the first k; but if all L are ≤ all R, then all L are among the smallest k? Actually consider S = [1,2,2,3], k=2, L={2,2}, R={1,3}. Here max(L)=2, min(R)=1, condition fails because 2 > 1. So that's not allowed. For condition to hold, L must be such that all L ≤ all R. In that case, in the sorted order, all L will come before any R, because any element of L is ≤ any element of R, so when sorting, L elements will be placed before R elements. Therefore, the first |L| elements in sorted order will be exactly the multiset L (since there are exactly |L| elements that are ≤ the smallest element of R, and those are precisely the elements of L? But there could be ties: If max(L) = min(R) = x, then some x's may be in L and some in R, but since they are equal, the sorted order could intermix them arbitrarily. However, the condition "all L ≤ all R" ensures that any element in L is ≤ any element in R; equality is allowed. In sorted order, the x's could be interleaved, but the multiset of the first k positions might not be exactly L if there are more x's in R? Let's examine: S = [1,2,2,2], k=2. Could L={1,2}, R={2,2}? Then max(L)=2, min(R)=2, condition holds (2 ≤ 2). Sorted order is [1,2,2,2]. The first two elements are 1 and 2. L={1,2} matches that multiset. Could L={2,2}, R={1,2}? Then max(L)=2, min(R)=1 => 2>1 fails. Could L={1,1}, R={2,2}? Works but then sorted order would have 1,1 first. That's fine. Could there be a scenario where L does not equal the first k smallest multiset? Suppose S = [1,1,2,2], k=2. L = {1,2}, R = {1,2}. Then max(L)=2, min(R)=1, condition fails (2>1). So not allowed. Suppose S = [1,2,3,3], k=2. L={1,3}, R={2,3}. max(L)=3, min(R)=2 -> fails. So seems that whenever condition holds, L must be exactly the k smallest. Formal proof: Suppose we sort S: s_1 ≤ s_2 ≤ ... ≤ s_n. Since all elements of L are ≤ all elements of R, we have that for any l ∈ L and r ∈ R, l ≤ r. This implies that the largest element in L is ≤ the smallest element in R. So all elements in L are ≤ the smallest element in R. Therefore, the k smallest elements of S (i.e., s_1,...,s_k) must all be ≤ the smallest element in R. But there are exactly k elements in L, all ≤ smallest in R. So the multiset of L must be exactly the multiset of the k smallest elements. Because if there was an element in L that is larger than some element in R, condition would be violated. Conversely, if L is exactly the k smallest, then clearly max(L) ≤ min(R). So they are equivalent.
Thus, the condition can also be expressed as: For each forbidden edge (i.e., where swap is not allowed), the maximum among a[1..i] must be ≤ minimum among a[i+1..n]? Actually careful: The forbidden edge is at position i, meaning we cannot swap across i and i+1. The two sides are indices 1..i and i+1..n. For sorting to be possible, we require that the multiset of values in left side equals the multiset of the i smallest values. That is equivalent to max(left) ≤ min(right). So we could simply check for each i from 1 to n-1, if i is not in p (i.e., edge not allowed), then check if max(a[1..i]) <= min(a[i+1..n]). If this holds for all forbidden edges, then answer YES. This is an alternative O(n) per test case (with precomputed prefix max and suffix min) which is efficient. But our component multiset approach also works and is straightforward.
Given constraints small, both are fine.
But we should be careful: The condition "max(left) ≤ min(right)" is necessary and sufficient? Let's double-check with an example: Suppose a = [2,1,3], allowed edges: only at position 2? Actually allowed edges maybe only p = [2] (so we can swap a[2] and a[3] but not a[1] and a[2]). Forbidden edge at position 1. Then left = [2], right = [1,3]. max left =2, min right = 1, 2 > 1 => would say NO. But can we sort? Allowed swaps: only swap (2,3). So we can get [2,3,1] by swapping 1 and 3? Actually initial [2,1,3]; swap (2,3) gives [2,3,1] not sorted. Cannot swap (1,2). So sorted array [1,2,3] unreachable. Indeed NO. Good.
Now consider a = [1,3,2,4], allowed edges at positions 1 and 3 only (so p = [1,3]). Forbidden edge at position 2. Check condition: For i=2 (forbidden), left = indices 1..2: [1,3]; max=3; right indices 3..4: [2,4]; min=2; 3>2 => NO. Let's see if sorting possible? Edges: swap (1,2) allowed, swap (3,4) allowed. So components: {1,2} and {3,4}. Original: component1 {1,3}, component2 {2,4}. Sorted target: [1,2,3,4]; component1 should be [1,2] but we have [1,3]; not same multiset -> NO. So condition works.
Now consider a case where condition holds but sorting is possible? Obviously. So the condition is both necessary and sufficient.
Proof: If we can't swap across i, then the elements that end up on left after any sequence of swaps must be exactly the set of elements initially on left (since no crossing). But note: Actually we cannot move elements across a forbidden edge at all. So the set of indices that are left side and right side remain invariant as sets of elements? Actually the elements can be rearranged within each side but cannot cross. So the multiset of values on the left side is invariant. Thus, for sorting to be possible, the invariant left multiset must equal the multiset of the i smallest values (since in sorted order, the left side contains exactly the i smallest). This is equivalent to max(left) ≤ min(right) as argued. Conversely, if for each forbidden edge the condition holds, then we can sort? Actually we also need that there may be multiple forbidden edges; the condition for each individually might guarantee that we can sort by handling each component? Let's see: If we have multiple forbidden edges, the components are separated. The condition for each forbidden edge ensures that the left side's multiset is the i smallest? But if we have multiple forbidden edges, the condition for the leftmost forbidden edge (i1) ensures that the left component (indices 1..i1) has the i1 smallest. For the next forbidden edge (i2), the left side is 1..i2. The condition for that edge ensures that the left side multiset of 1..i2 equals the i2 smallest. But that condition, combined with the previous, ensures that the segment between i1+1 and i2 has the appropriate multiset? Actually we need a consistent assignment. The condition that each "cut" has the correct property is equivalent to the component-wise multiset condition. So yes.
Thus both methods are valid.
Given the constraints, we can just implement the component method which is simple.
One more nuance: Since p values are distinct but not necessarily sorted, we sort p? Not needed.
Now write final answer.
But wait, there is an alternative approach: Because m < n and n ≤ 100, we could also simulate bubble sort using allowed swaps and see if we can sort. That would be O(n^2) per test, also fine. But we have better.
Thus final code.
Now produce final answer with explanation. ```python
import sys
def solve() -> None:
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it))
m = int(next(it))
a = [int(next(it)) for __ in range(n)]
p = [int(next(it)) for __ in range(m)]
# allowed[i] : can we swap a[i] and a[i+1] ? (0‑based index for edges)
allowed = [False] * (n - 1)
for pos in p:
allowed[pos - 1] = True
# build connected components (contiguous segments)
comps = []
i = 0
while i < n:
start = i
while i < n - 1 and allowed[i]:
i += 1
# component from start to i (inclusive)
comps.append((start, i))
i += 1
sorted_a = sorted(a)
ok = True
for l, r in comps:
# multisets must match
if sorted(a[l:r+1]) != sorted_a[l:r+1]:
ok = False
break
out.append("YES" if ok else "NO")
sys.stdout.write("\n".join(out))
if name == "main":
solve()