You are given an array aa of length nn.
You are also given a set of distinct positions p_1, p_2, \dots, p_mp1,p2,…,pm, where 1 \le p_i < n1≤pi<n. The position p_ipi means that you can swap elements a[p_i]a[pi] and a[p_i + 1]a[pi+1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 \le a_2 \le \dots \le a_na1≤a2≤⋯≤an) using only allowed swaps.
For example, if a = [3, 2, 1]a=[3,2,1] and p = [1, 2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a = [3, 1, 2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a = [1, 3, 2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a = [1, 2, 3]a=[1,2,3], sorted in non-decreasing order.
You can see that if a = [4, 1, 2, 3]a=[4,1,2,3] and p = [3, 2]p=[3,2] then you cannot sort the array.
You have to answer tt independent test cases.
题意:给出打乱顺序的1~n的数,和m个数代表位置(假设给的x那么就可以交换x和x+1的数),最终使其变为从小到大的顺序。
思路:首先找到两个顺序不一样的数,如果在这之间存在不能交换的位置,那么就一定不能完成。
反之则可以完成。
#include<iostream>
using namespace std;
const int N = 110;
int a[N];
int b[N]; //用来记录位置是否可以交换。
int flag; // 记录是否可以完成交换。
int main()
{
int t;
cin >> t;
while (t--)
{
int n, m,x;
memset(b, 0, sizeof(b));
cin >> n >> m;
for (int i = 1; i <= n; ++i) cin >> a[i];
while (m--)
{
cin >> x;
b[x] = 1; //记录哪个位置可以交换。
}
for (int i = 1; i <= n; ++i)
{
flag = 0;
for (int j = i + 1; j <= n; ++j)
{
if (a[i] > a[j])
{
for (int k = i; k < j; ++k)
{
if (!b[k])
{
flag = 1;
break;
}
}
if (flag) break;
}
if (flag) break;
}
if (flag) break;
}
if (flag) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}